当玩家射击时,子弹飞到屏幕中央。但是如果玩家离某个物体太近,那么子弹就不会撞到中心,因为它会从屏幕右侧的枪中飞出来。我该如何解决这个问题?
public Rigidbody projectile;
public int speed = 50;
public Transform startBulletPosition;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody clone;
clone = Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody;
var centre = new Vector3(0.5f, 0.5f, 0f);
var ray = Camera.main.ViewportPointToRay(centre);
clone.velocity = ray.direction * speed;
}
}
答案 0 :(得分:2)
public Rigidbody projectile;
public Transform startBulletPosition;
public float speed;
public float rotationSpeed;
public Camera camera;
Vector3 startingDirection;
void Start() {
startingDirection = startBulletPosition.transform.forward;
}
void Update() {
if (Input.GetButtonDown("Fire1")) {
RaycastHit hit;
Vector3 targetDirection;
if (Physics.Raycast(Camera.main.transform.position, camera.transform.forward, out hit)){
targetDirection = hit.transform.position - startBulletPosition.position;
} else {
targetDirection = startingDirection;
}
Vector3 newDirection = Vector3.RotateTowards( startBulletPosition.transform.forward, targetDirection, rotationSpeed * Time.deltaTime, 0.0f);
startBulletPosition.transform.forward = newDirection;
Rigidbody clone;
clone = Instantiate(projectile, startBulletPosition.position, startBulletPosition.rotation) as Rigidbody;
clone.velocity = targetDirection * speed;
}
}
我会从相机位置做一个Raycast,看看你能击中什么,然后将武器旋转到那个方向。如我的示例代码中所示。该武器将准确指向您的相机Raycast击中的中心视图。
此外,您可以通过该公共浮动来控制最大速度。这将是一个很好的武器运动而不仅仅是瞬间跳跃。
以下是我在此代码段中使用的文档链接: https://docs.unity3d.com/ScriptReference/RaycastHit.html https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
如果光线投射未命中,将使用存储的武器原始方向。 (假设startBulletPosition是武器的变换......)
如果需要,可以将maxDistance参数添加到Physics.Raycast调用中,以限制此行为处于活动状态的距离。