试图编写一个C#代码,使导弹跟随Unity中的玩家

时间:2018-06-04 11:13:57

标签: c# unity3d game-engine projectile targeting

我已经尝试了两天没有成功。我无法弄清楚我在哪里错过了这一点。所有导弹都朝着目标的位置移动但不跟随它。该位置保持不变,所有新制造的导弹都达到了这一点,而不是跟随目标。

以下是代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HomingMissile : MonoBehaviour
{
    private GameObject target; //changed to private
    private Rigidbody rb;
    public float rotationSpeed;
    public float speed;

Quaternion rotateToTarget;
Vector3 direction;

private void Start()
{
    target = GameObject.FindGameObjectWithTag("Player"); //uncommented this
    rb = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    //made some modifications
    Vector3 direction = (target.transform.position - transform.position).normalized;
    float angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;//interchanged x and z
    Quaternion rotateToTarget = Quaternion.Euler(0, angle, 0);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
    Vector3 deltaPosition = speed * direction * Time.deltaTime;
    rb.MovePosition(transform.position + deltaPosition);

}

}

我使用检查器选择了目标(变换)。 我明白你使用Unity和C#。

我试图实现的是导弹应该实时跟踪目标的位置。我可以自己添加导弹的破坏代码。 注意: 请不要将此标记为重复。它不是。 游戏是2D,Y总是不变的。垂直轴为X,水平轴为X.对象为3D。这就是为什么我不能使用rigidbody2D。

编辑: 代码已编辑。导弹跟随目标并指向运动方向。如何使导弹在需要旋转时进行圆周旋转?

1 个答案:

答案 0 :(得分:3)

首先,考虑一下:

改为使用rigidbody.movePosition()rigidbody.moveRotation()。这是一个例子:

Vector3 dir = (target.transform.position - transform.position).normalized;
Vector3 deltaPosition = speed * dir * Time.deltaTime;
rb.MovePosition(transform.position + deltaPosition);

自己尝试rigidbody.MoveRotation()进行练习。

最后,要了解有很多方法可以实现导弹的归位。 Here's one that is commonly used in real life.

编辑:我不建议使用rb.addForce(),因为如果你试一试,你会发现它太不确定了。

相关问题