我正在创建一款 2D 游戏,目前有三个主要脚本:一个用于自由落体的垂直运动,一个用于水平运动和一个相机跟随脚本。每当我将目标对象附加到相机跟随脚本时,水平移动就会停止工作,而垂直移动则很好。这里可能有什么问题?
水平运动:
public class HorizontalMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float horizontalBoundary = 3.5f; // Maximum left and right boundaries for the object
void Update()
{
// Horizontal movement (left and right)
float horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * moveSpeed * Time.deltaTime);
// Clamp the object's position to stay within the horizontal boundaries
float clampedXPosition = Mathf.Clamp(transform.position.x, -horizontalBoundary, horizontalBoundary);
transform.position = new Vector3(clampedXPosition, transform.position.y, transform.position.z);
}
}
相机跟随;
public class CameraFollow : MonoBehaviour
{
public Transform target; // Reference to the falling object's Transform
public Vector3 offset = new Vector3(0f, 0f, -10f); // Adjust the camera's offset if needed
void LateUpdate()
{
if (target != null)
{
// Update the camera's position to match the falling object's position
transform.position = target.position + offset;
}
}
}
垂直运动:
public class PlayerMovement : MonoBehaviour
{
public float fallSpeed = 3f; // Speed at which the object falls
void Update()
{
// Vertical falling movement
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime);
}
}
我尝试了一切我能做的,因为我认为也许更新而不是 LateUpdate 会起作用,尝试附加其他目标,除了这个之外一切都很好。