【发布时间】:2019-09-22 18:20:19
【问题描述】:
我正在开发基于 Unity 盒子物理的游戏,为此我正在推动盒子。我希望玩家能够在 X 轴上围绕框移动相机,但这意味着如果玩家将相机移动到框的背面,则移动会反转。
我曾尝试查看其他帖子/教程,但没有人能做我想做的事。
这是我的玩家移动代码,
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
Rigidbody rb;
public float forwardBackForce = 1000f;
public float leftRightForce = 1000f;
// Gets component Rigidbody
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Used for movement
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
rb.AddForce(0, 0, forwardBackForce * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
rb.AddForce(0, 0, -forwardBackForce * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
rb.AddForce(-leftRightForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
rb.AddForce(leftRightForce * Time.deltaTime, 0, 0);
}
}
}
这是我的相机移动代码,
using System.Collections.Generic;
using UnityEngine;
public class playerCamera : MonoBehaviour
{
public Transform PlayerTransform;
private Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
public float SmoothFactor = 0.05f;
public bool LookAtPlayer = false;
public bool RotateAroundPlayer = true;
public float RotationSpeed = 5.0f;
// Start is called before the first frame update
void Start()
{
_cameraOffset = transform.position - PlayerTransform.position;
}
// LateUpdate is called after Update
void LateUpdate()
{
if(RotateAroundPlayer)
{
Quaternion camTurnX = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotationSpeed, Vector3.up);
_cameraOffset = camTurnX * _cameraOffset;
}
Vector3 newPos = PlayerTransform.position + _cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);
if (LookAtPlayer || RotateAroundPlayer)
transform.LookAt(PlayerTransform);
}
}
我所需要的只是一种让玩家相对于相机移动的方法。
最后一点是我正在开发一个碰撞系统,所以盒子不能一直推到墙上。
【问题讨论】: