通过前面介绍,已经实现第三人称的角色控制,但有一个问题,当你上下地查看时,可以把整个场景翻转过来,如下图:
这种场景,往往我们是不希望出现的,毕竟不是在开飞机。那么怎么办呢?这时,我们就要想办法了,控制头的旋转角度,不要让它360度地旋转了。如果我们要限制在-80到80度之间,那么怎么样来实现呢?估计你首先会想到使用if语句来判断,其实可以使用Mathf.Clamp函数实现同样的功能。可以查看到这个函数定义如下:
public static float Clamp(float value, float min, float max);
限制value的值在min和max之间, 如果value小于min,返回min。 如果value大于max,返回max,否则返回value。
通过此函数的了解,因此,我们只需要把将要改变的旋转值放到第一个参数,后面两个参数分别设置最小值和最大值,就可以限制旋转的角度了。因而,我们需要脚本文件BasicMovement.cs里定义一个变量来跟踪头的旋转角度,如下:
private float currentHeadRotation = 0;
可以看这行代码采用private为定义,也就是说这个变量只能在本类使用,别的地方不能操作。同时,private声明的变量不会在inspector里查看到,不能在里面修改。因而很多私有的数据,都要来定义为private,这样防止别的类乱修改,或者界面上作修改。为了修改方便,我们同样定义两个公共属性的最小值和最大值变量,如下:
public float maxHeadRotation = 80.0f;
public float minHeadRotation = -80.0f;
这时,万事俱备只欠东风,要开始使用函数Mathf.Clamp了,因此,整个代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicMovement : MonoBehaviour {
public float speed = 10.0f;
public float rotationSpeed = 2.0f;
public Transform head;
public float maxHeadRotation = 80.0f;
public float minHeadRotation = -80.0f;
private float currentHeadRotation = 0;
// 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);
gameObject.GetComponent<CharacterController>().Move(transform.TransformDirection(input * speed * Time.deltaTime));
Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
transform.Rotate(Vector3.up, mouseInput.x * rotationSpeed);
//Debug.Log(mouseInput.x + ":" + mouseInput.y);
//head.Rotate(Vector3.left, mouseInput.y * rotationSpeed);
currentHeadRotation = Mathf.Clamp(currentHeadRotation + mouseInput.y * rotationSpeed, minHeadRotation, maxHeadRotation);
head.localRotation = Quaternion.identity;
head.Rotate(Vector3.left, currentHeadRotation);
}
}
对比旋转的代码,可以看到,当前角度currentHeadRotation加上鼠标变化的值,如果在范围内,就返回相应的值,如果不在,就返回边界值。然后设置head的旋转位置为Quaternion.identity,这是什么意思呢?Quaternion.identity就是指Quaternion(0,0,0,0),就是每旋转前的初始角度,是一个确切的值。transform.localRotation属性一般使用四元数赋值,通过Quaternion可以将欧拉角转化为四元数,表示当前旋转角度。因此,这段代码的意思,就是每次head要旋转之前,先复位,再进行旋转。旋转还是调用函数head.Rotate来实现的。如果不进行复位的动作,会发现后一个旋转是前一个旋转基础之上进行的。
经过这样的修改,你再尝试play这个游戏,可以看到不会再颠倒场景了。增加的变量如下图显示:
如果你想限制其它角度值,就可修改80到-80之间的值。
Python游戏开发入门
http://edu.csdn.net/course/detail/5690
你也能动手修改C编译器
http://edu.csdn.net/course/detail/5582