用键盘“上-下-左-右”四个建实现unity中camera的“前进-后退-左转-右转”的功能。此处只是考虑了水平方向上的移动,(如果涉及到垂直方向那岂不是可以上天入地,不太实际。)但如果要实现垂直就要用到高中数学的稍稍复杂的三维计算了,以后有时间再补吧。
感觉三维图不太好画,所以就不讲解原理了。直接上代码。
新建一个名为CameraController的cs文件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float speed_angel;//转弯的角速度
public float speed_move;//前进-后退速度
private Vector3 vr;//辅助计算的一个向量
private Vector3 rota;//可以不用的,就是记录当前rotation
private Vector3 v;//一个有三维方向的矢量速度
// Start is called before the first frame update
void Start()
{
//初始化,不在定义的时候初始化主要是因为不懂unity的实时更新机制
speed_angel = 5.0f;
speed_move = 1.0f;
vr = new Vector3(0, 1.0f, 0);
rota = new Vector3(0, 0, 0);
v = new Vector3(0, 0, 1);
transform.rotation = Quaternion.Euler(rota);
}
// Update is called once per frame
void Update()
{
//获取左-右键按下的时长,就是左右转的角度
float righ = Input.GetAxis("Horizontal") * speed_angel;
//获取上-下键按下的时长,就是前进后退的距离
float forward = Input.GetAxis("Vertical") * speed_move;
//物体进行旋转操作
transform.Rotate(vr*righ);
//速度方向进行改变
v.z = Mathf.Cos(rota.y/180);
v.x = Mathf.Sin(rota.y/180);
//前进后退移动
Vector3 move = v * forward;
transform.Translate(move);
}
}
把这个CameraController.cs挂载到main camera下就行了。
补上一个可以鼠标控制改变视角的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float speed_angel = 5.0f;
public float speed_move = 2.0f;
private float aup=0.0f;
private Vector3 vr = new Vector3(0,1.0f,0);
private Vector3 rota = new Vector3(0, 0, 0);
private Vector3 v = new Vector3(0, 0, 1);
private float PI = Mathf.Acos(-1.0f);
// Start is called before the first frame update
void Start()
{
speed_angel = 5.0f;
speed_move = 1.0f;
vr = new Vector3(0, 1.0f, 0);
rota = new Vector3(0, 0, 0);
v = new Vector3(0, 0, 1);
transform.rotation = Quaternion.Euler(rota);
}
// Update is called once per frame
void Update()
{
float righ = Input.GetAxis("Horizontal") * speed_angel;
float forward = Input.GetAxis("Vertical") * speed_move;
float up = 0;
if (Input.GetKey(KeyCode.Mouse0))
{
float horizontalSpeed = 2.0f;
float verticalSpeed = 2.0f;
float v = horizontalSpeed * Input.GetAxis("Mouse X") * speed_angel;
up = verticalSpeed * Input.GetAxis("Mouse Y");
aup += up;
aup = (aup > 80 ? 80 : aup);
aup = (aup < -80 ? -80 : aup);
righ -= v;
}
transform.Rotate(vr*righ);
rota.y+=vr.y*righ;
v.z = Mathf.Cos(aup/180*PI);
v.y = Mathf.Sin(aup/180*PI);
transform.rotation = Quaternion.Euler(new Vector3(aup, rota.y, 0.0f));
rota = new Vector3(aup, rota.y, 0.0f);
Vector3 move = v * forward;
transform.Translate(move);
}
}