移动与旋转 1
player角色随asdw按键左右上下移动并旋转
public void Update()
{
// Reset player rotation to look in the same direction as the camera.
Quaternion tempRotation = myCamera.transform.rotation;
tempRotation.x = ;
tempRotation.z = ;
myTransform.rotation = tempRotation; float xMovement = Input.GetAxis("Horizontal");// The horizontal movement.
float zMovement = Input.GetAxis("Vertical");// The vertical movement. // Are whe grounded, yes then move.
if (IsGrounded()) { //Move player the same distance in each direction. Player must move in a circular motion.
float tempAngle = Mathf.Atan2(zMovement,xMovement); //获取到键盘输入的弧度 xMovement *= Mathf.Abs(Mathf.Cos(tempAngle));//将键盘坐标系的弧度转换为新坐标系的x坐标(当斜边为1时cos弧度求到x)
zMovement *= Mathf.Abs(Mathf.Sin(tempAngle));//同理求到y moveDirection = new Vector3(xMovement, , zMovement); //得到方向 moveDirection = myTransform.TransformDirection(moveDirection);
moveDirection *= moveSpeed; // Make the player jump.
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed; //跳跃
// TODO Add jump animation.
}
} // Apply gravity.
moveDirection.y -= gravity * Time.deltaTime; //重力 // Are we moving.
if(moveDirection.x == && moveDirection.z == )
{
if(animator!=null)
{
animator.SetBool("run", false); //停止移动后停止播放动画
}
}
else
{
// Make rotation object(The child object that contains animation) rotate to direction we are moving in.
Vector3 temp = myTransform.position;
temp.x += xMovement; //得到下一个目标点
temp.z += zMovement;
myRotationObject.localRotation = Quaternion.Slerp(myRotationObject.localRotation, Quaternion.LookRotation(temp-myTransform.position), rotationSpeed * Time.deltaTime); //使角色平滑转向下一个目标点
if(animator!=null)
{
animator.SetBool("run", true);
}
} controller.Move(moveDirection * Time.deltaTime); //开始移动
}