我们在玩FPS游戏的时候,移动鼠标那么第一人称视角就会发生改变
今天我们来实现 先实现第三人称的旋转功能
首先我们要了解旋转使用哪个属性
其实我们在实现小球围绕旋转就写过类似的,详细请看以前文章
第一步 通过WASD 来旋转物体
1.创建Cube对象:使用它来实现旋转
2.创建Plane对象:有参照物我们就可以判断是否在移动
2.Project层级 Assets下
创建Scripts文件
用来装MoveForce脚本
层级关系如下
3.编写脚本MoveForce
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForce : MonoBehaviour
{
private Rigidbody m_rigidbody;//变量定义:开辟空间
public float speed=3.0f;
// Start is called before the first frame update
void Start()
{
m_rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
//Update 不能不保证固定时间,不同配置给出反馈时间不同
//FixedUpdate是没0.02秒调用一次
void FixedUpdate()
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
//旋转是改变transform 下的Rotate属性
transform.Rotate(new Vector3(horizontal, 0, vertical) * speed); }
}
然后将脚本拖给Cube身上
点击运行,我们通过wasd看看Cube有没有旋转
第二步,我们通过鼠标来让Cube旋转
重新书写脚本MoveForce
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForce : MonoBehaviour
{
private Rigidbody rigidbody;//变量定义:开辟空间
public float speed;
private float m_MouseSensitivity= 3.0f;//控制鼠标敏感度
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
//Update 不能不保证固定时间,不同配置给出反馈时间不同
//FixedUpdate是没0.02秒调用一次
void FixedUpdate()
{
float vertical = Input.GetAxis("Mouse Y");
float horizontal = Input.GetAxis("Mouse X");
//第一种
transform.Rotate(vertical * m_MouseSensitivity, horizontal * m_MouseSensitivity, 0);
//第二种
//第一人称扭头代码
//四元数公式是以乘积的方式进行,如果都是四元数t*p,优先执行t后执行p
//var rotation = transform.rotation * Quaternion.AngleAxis(horizontal*m_MouseSensitivity,Vector3.up)
//*Quaternion.AngleAxis(vertical * m_MouseSensitivity, Vector3.left);
//transform.rotation = rotation;
}
}
上述讲了通过WASD改变物体的Rotate来达到旋转
还有通过移动鼠标来实现旋转的两种方法
最后实现可能不尽如意,比如我不可能在FPS游戏种上下的旋转达到360°,原地后空翻吗?
所以还是要有时间去学习一下C#语言,让上下旋转角度小于180°