【问题标题】:Trying to write a C# code to make a missile follow the player in Unity尝试编写 C# 代码以使导弹在 Unity 中跟随玩家
【发布时间】:2018-06-04 11:13:56
【问题描述】:

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

代码如下:

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#,显然你知道这一点。

我试图实现的是导弹应该实时跟踪目标的位置。我可以自己添加导弹的销毁代码。 注意: 请不要将此标记为重复。它不是。 游戏是二维的,其中 Y 始终是常数。垂直轴是 X,水平轴是 X。对象是 3D。这就是为什么我不能使用rigidbody2D。

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

【问题讨论】:

  • 在我看来,目标转换不正确。它指的是一个未使用的游戏对象
  • 我尝试了两种方式。使用检查器拖放目标变换并使用 target = GameObject.FindGameObjectWithTag("Target");但它不起作用。
  • 代码没问题。尝试调试转换以查看它所遵循的位置
  • 调试日志:(0.0, 0.0, 0.0) UnityEngine.Debug:Log(Object) HomingMissile:FixedUpdate()(在 Assets/Test/HomingMissile.cs:38)。
  • 所以您现在知道当前目标始终为零。正如我所说,这个脚本遵循了错误的目标

标签: c# unity3d game-engine projectile targeting


【解决方案1】:

首先,考虑:

请改用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(),因为如果你尝试一下,你会发现它太不确定了。

【讨论】:

  • 感谢您的回复。但问题并没有解决。无论目标的位置如何,导弹的所有实例都大约接近原点(0.x,0.x,0.x)。我确保没有其他脚本干扰导弹。重力被引爆。导弹仍然没有旋转。
  • @Joe_Vj_95 用您使用的最新代码更新您的问题?
  • 添加了修改后的代码。我接受你的回答。因为它也有助于使其发挥作用。导弹的旋转并不像预期的那样。有什么办法可以让导弹在需要旋转的时候做圆周旋转?
  • @Joe_Vj_95 如果您正在操作rigidbody,请不要修改transform.rotation。在统一中,要么 直接操作变换 操作刚体(物理)。不建议两者都做(检查文档)。改用rigidbody.moveRotation()。
  • 我是 Unity 和 C# 的新手。仅仅1周的经验。你是在建议这个吗?用rb.MoveRotation(rotateToTarget);替换//transform.rotation = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
猜你喜欢
  • 2020-03-20
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多