我对Unity感到陌生(从几天前开始)。
我正在尝试创建一种功能,使相机始终跟随滚球,但是在保持聚焦于主要对象的同时,也应通过箭头键控制相机。
我有以下代码跟随实际对象:
using UnityEngine;
public class FollowPlayer : MonoBehaviour {
public Transform player;
private Vector3 offset = new Vector3(0, 3, -5);
// Update is called once per frame
void Update() {
transform.position = player.position + offset;
}
}
上面的代码工作完美,它随对象移动而移动。
但是我尝试了以下方法来移动相机:
using UnityEngine;
public class FollowPlayer : MonoBehaviour {
public Transform player;
public GameObject MainCamera;
public Vector3 offset = new Vector3(0, 3, -5);
private Vector3 RotateOffset;
public float rotateJump = 1f;
// Update is called once per frame
void Update() {
//Rotate Camera 90 degrees Left
if (Input.GetKey("left")) {
RotateOffset = new Vector3(transform.position.x - rotateJump, 0, transform.position.z - rotateJump);
transform.position = player.position + RotateOffset;
}
//Rotate Camera 90 degrees Right
if (Input.GetKey("right")) {
RotateOffset = new Vector3(transform.position.x + rotateJump, 0, transform.position.z + rotateJump);
transform.position = player.position + RotateOffset;
}
}
}
但这只会将相机从位置A沿直线移动到位置B,如下所示,而不会旋转:
如何让相机跟随物体并仍由用户控制?
谢谢!
我在板上移动对象的代码如下:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float MovementForce = 200f;
void FixedUpdate() {
//Move Forward
if (Input.GetKey("w")) {
rb.AddForce(0, 0, MovementForce * Time.deltaTime);
}
//Move Left
if (Input.GetKey("a")) {
rb.AddForce(-MovementForce * Time.deltaTime, 0, 0);
}
//Move Back
if (Input.GetKey("s")) {
rb.AddForce(0, 0, - MovementForce * Time.deltaTime);
}
//Move Right
if (Input.GetKey("d")) {
rb.AddForce(MovementForce * Time.deltaTime, 0, 0);
}
}
}
编辑:
我更新了FollowPlayer脚本,如下所示:
using UnityEngine;
public class FollowPlayer : MonoBehaviour {
public Transform player;
private Vector3 offset = new Vector3(0, 3, -5);
private float RotateVal = 2f;
private Vector3 VPanAmount = new Vector3(2, 0, 0);
private Vector3 HPanAmount = new Vector3(0, 2, 0);
private Vector3 VRotatoinOffset;
private Vector3 HRotatoinOffset;
private void Start() {
}
// Update is called once per frame
void Update() {
if (Input.GetKey("left")) {
VRotatoinOffset = player.position + offset - VPanAmount;
transform.Rotate(0, -RotateVal, 0);
}
if (Input.GetKey("right")) {
VRotatoinOffset = player.position + offset + VPanAmount;
transform.Rotate(0, RotateVal, 0);
}
if (Input.GetKey("up")) {
HRotatoinOffset = player.position + offset + HPanAmount;
transform.Rotate(-RotateVal, 0, 0);
}
if (Input.GetKey("down")) {
HRotatoinOffset = player.position + offset + HPanAmount;
transform.Rotate(RotateVal, 0, 0);
}
transform.position = player.position + offset - VRotatoinOffset - HRotatoinOffset;
}
}
摄像机会随着对象的移动而旋转和移动,但是摄像机的焦点不会停留在对象上,并且摄像机会跳到运动场以下。