描述
实现摄像机根据鼠标移动跟随物体旋转,以摄像机前物体为中心,摄像机围绕物体旋转,并使摄像机时刻指向物体
实现效果
Unity 组件设置
Camera 组件设置
Body 组件设置
实现代码
CameraRotateMove.cs 摄像机跟随和旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMoveRotate : MonoBehaviour
{
public float LerpPar;
public Transform FollowTrans;
public Vector3 Offset;
public Transform CameraTransform1;
Vector3 ForwardDirec;
// Start is called before the first frame update
void Start()
{
Offset = transform.position - FollowTrans.position;
}
// Update is called once per frame
void Update()
{
float dx = Input.GetAxis("Mouse X");
Offset = Quaternion.AngleAxis(dx * 10, Vector3.up) * Offset;
transform.position = Vector3.Lerp(transform.position, (FollowTrans.position + Offset), LerpPar * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(-1 * Offset);
}
}
move_better.cs 物体根据按键移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move_better : MonoBehaviour
{
public float speed = 3.0f;
private Rigidbody mRigidbody;
public Transform FollowTrans;
public Vector3 Offset;
public Transform CameraTrans;
float Offset_x, Offset_z;
// Start is called before the first frame update
void Start()
{
mRigidbody = GetComponent<Rigidbody>();
Offset = FollowTrans.position - CameraTrans.position;
}
// Update is called once per frame
void Update()
{
Offset = FollowTrans.position - CameraTrans.position;
Vector3 direction_forward = new Vector3(0, 0, Offset_z);
Vector3 direction_left = new Vector3(Offset_x, 0, 0);
if (Input.GetKeyDown("w"))
{
mRigidbody.velocity = CameraTrans.forward * speed;
}
if (Input.GetKeyDown("s"))
{
mRigidbody.velocity = -1 * CameraTrans.forward * speed;
}
if (Input.GetKeyDown("a"))
{
mRigidbody.velocity = -1 * CameraTrans.right * speed;
}
if (Input.GetKeyDown("d"))
{
mRigidbody.velocity = CameraTrans.right * speed;
}
if (Input.GetKeyDown("space"))
{
mRigidbody.velocity = 2 * Vector3.up * speed;
}
}
}