- 最后登录
- 2014-10-23
- 注册时间
- 2011-7-19
- 阅读权限
- 90
- 积分
- 81303
- 纳金币
- -1
- 精华
- 11
|
Finishing touches
If you try to play the game now, you will see the character moving around. Fantastic!!
He seems a little stubborn and doesn’t want to turn at all though. We will fix that next.
transform.rotation = Quaternion.LookRotation(moveDirection);
this takes the transform (the main orientation of game object), and rotates it by moveDirection. We already set up moveDirection earlier for the angle we want it to be at.
Success…but wait. If you take your hand away from the controls for a second, he will auto-magically rotate back facing right. Dang!
So close. One more thing to fix that. Wrap this if statement around the last line you put in. It should look like this.
if (targetDirection != Vector3.zero) { transform.rotation = Quaternion.LookRotation(moveDirection); }
What this does is that the game object will only try to rotate if the targetDirection is NOT zero. When you take you hand away from the keyboard for a split second, the input values will show (0,0,0), so it thinks that is the target direction.
It isn’t,but it doesn’t know that. The only time that value will show is when you take your hands off, so the if statement simply ignores input when you take your hands off everything.
One last thing. Add this after the entire Update function at the bottom:
@script RequireComponent(CharacterController)
This will make sure a Character Controller component is attached to the game object that the script is attached to. If you forget to add one and you press play, this line will automatically add a component to the game object and save you from a nasty error.
Hit play and watch your character move and rotate around.
Final Thoughts
If for some reason you scrolled down to get the source without reading anything, here is the project set up files and source.
This is a good first step in understanding how basic character movement is put together. A fully done character is complicated, but understanding these concepts are fundamental to building more advanced setups. This set up might seem weird with how the character moves, but when a camera is added along with a few other elements later, it will all make sense. I will try to continue where this example leaves off and explain more with collisions and actions like jumping in the next post.
由 uke 发表 |
|