【发布时间】:2016-12-20 19:30:43
【问题描述】:
我有一个使用 c# 的统一游戏。在这个游戏中,我有一个滚动的球。我想用鼠标和WASD键旋转相机。
这意味着当我使用 W 时它应该向前,但是如果我旋转了我的相机,向前的方向也应该改变(所以相机总是在球的后面) 我已经制作了一个可以完成这项工作的脚本,但是有一个问题; 当我使用 S 键返回时,球开始向后飞!我该如何解决这个问题?
我认为发生这种情况是因为相机的角度看球。 另外,我前进的时候,速度有点慢,所以我认为相机的角度对移动有一些影响。也许我应该删除角度效果?
这是我的脚本:
播放器控制脚本
using UnityEngine;
using System.Collections;
public class playercontroller2 : MonoBehaviour
{
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Use this for initialization
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
movement = Camera.main.transform.TransformDirection(movement);// this make ball goes in right direction ( W will be the place that camera looking )
rb.AddForce(movement * speed * Time.deltaTime);
}
}
相机脚本
public float turnSpeed = 4.0f;
public Transform player;
private Vector3 offset;
public float zoomStep = 30f;
public float zoomSpeed = 5f;
private float heightWanted;
private float distanceWanted;
private Vector3 zoomResult;
private Quaternion rotationResult;
private Vector3 targetAdjustedPosition;
public float height = 20f;
public float distance = 20f;
public float min = 10f;
public float max = 60;
void Start () {
// _offset = new Vector3(0, 22, 33);
offset = transform.position - player.transform.position;
offset = new Vector3(player.position.x, player.position.y + 8.0f, player.position.z + 7.0f);
}
// Update is called once per frame
void LateUpdate()
{
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
transform.position = player.position + offset;
transform.LookAt(player.position);
}
void Update()
{
float mouseInput = Input.GetAxis("Mouse ScrollWheel");
heightWanted -= zoomStep * mouseInput;
distanceWanted -= zoomStep * mouseInput;
// Make sure they meet our min/max values.
heightWanted = Mathf.Clamp(heightWanted, min, max);
distanceWanted = Mathf.Clamp(distanceWanted, min, max);
height = Mathf.Lerp(height, heightWanted, Time.deltaTime * zoomSpeed);
distance = Mathf.Lerp(distance, distanceWanted, Time.deltaTime * zoomSpeed);
// Post our result.
zoomResult = new Vector3(0f, height, -distance);
}
}
所以要明确一点,当我使用这个脚本时,当我按回(S 或向下箭头)时,球开始向后飞,但我在其他方向没有这个问题。
【问题讨论】:
-
只有时间发表评论。 Camera.main.transform 将导致 W 直接在远离相机的地方添加一个力,而 S 将添加一个第二个相机的力。我敢打赌,如果你把摄像头放在地下 W 会坏,而 S 会正常工作。
-
是的,如果我把相机放在地上可能没问题,但我希望相机总是从上往下看(比如 45 度,许多第三人称游戏都在使用)
标签: c# unity3d game-physics