游戏制作之路(9)角色实现旋转的功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caimouse/article/details/82256721

前面介绍了实现父子的层次关系,并且对角色添加一个鼻子,以便我们可以分辨角色的方向。现在要继续实现角色旋转的功能,角色的移动采用方向键来实现,那么旋转方向就不能使用它了,在这里采用鼠标来实现。
首先把鼻子的碰撞体去掉,如下:

选择nose物体,然后在右边box collider上右击右键,弹出菜单选择remove component,就可以删除鼻子的碰撞体。

仿照前面的运动速度一样,也要有一个调整旋转速度的参数,因此在代码里增加一行代码,如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicMovement : MonoBehaviour {

    public float speed = 10.0f;
    public float rotationSpeed = 2.0f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        //transform.position += input * speed * Time.deltaTime;
        gameObject.GetComponent<CharacterController>().Move(input * speed * Time.deltaTime);
    }
}

主要增加这行:

 public float rotationSpeed = 2.0f;

在界面上面显示如下:

后面,同样可以通过这里界面来调整旋转速度。

接着下来,我们要构造一个二维的向量来保存鼠标的旋转方向,也许你会问为什么只用二维的向量,而不用三维呢?因为鼠标是一个平面二维的输入,只有X轴方向和Y轴方向,因此只需要使用二维向量Vector2就可以了。所以把代码写成下面这样:

Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        transform.Rotate(Vector3.up, mouseInput.x * rotationSpeed);

第一行代码是从鼠标构造一个二维向量,第二行代码使用transform.Rotate函数,这个函数定义如下:

扫描二维码关注公众号,回复: 3079609 查看本文章

public void Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self);

函数第一个参数是绕着旋转的轴,第二个参数是旋转的角度。因此,transform.Rotate表示角色对象根据鼠标移动来旋转多少度。不过,这个函数你也许还是有点迷糊的,因为你不知道角度正值怎么样旋转,负值又是怎么样旋转?这时,你就需要了解unity的坐标系统是左手法则,还是右手法则,只有理解这点才知道它是向右,还是向左转的,如下:

从unity里可以看到,它是符合左手法则的,大母指指向方向向量的位置,然后四个手指方向就是正角度的旋转方向。

因此,前面这句语句,旋转轴是Vector3.up向上的方向轴,然后正值向右方向转动,负值向左手方向转动。

最后把代码改成这样:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicMovement : MonoBehaviour {

    public float speed = 10.0f;
    public float rotationSpeed = 2.0f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        //transform.position += input * speed * Time.deltaTime;
        gameObject.GetComponent<CharacterController>().Move(input * speed * Time.deltaTime);

        Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        transform.Rotate(Vector3.up, mouseInput.x * rotationSpeed);
    }
}

再点击play来运行,通过鼠标左右移动,就可以让角色进行360度旋转了。

运行之后,你是否会发现有一个问题呢?下一次再告诉你。

俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/82256721
今日推荐