Search code examples
c#unity-game-enginegame-engineprojectiletargeting

Trying to write a C# code to make a missile follow the player in Unity


I have been trying this for two days with no success. I cant figure out where I'm missing the point. All the missiles are moving towards the position of the target but not following it. The position remains fixed and all the newly created missiles come to this point instead of following the target.

Here is the code:

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);

}

}

I selected the target(transform) using the inspector. I'm using Unity and C# obviously you know that.

What Im trying to achieve is that the missile should follow the position of the target in real time. And i can add the destroy code for the missile myself. Note : Please don't tag this as a duplicate. It is not. The game is 2D where Y is always constant. Vertical axis is X and Horizontal axis is X. The objects are 3D. That's why I can't use rigidbody2D.

EDIT: Code edited. The missile follows the target and also points to the direction of motion. How to make the missile make a circular rotation when it needs to rotate?


Solution

  • Firstly, consider:

    Use rigidbody.movePosition() and rigidbody.moveRotation() instead. Here's an example:

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

    Try out rigidbody.MoveRotation() yourself for practice.

    Finally, understand that there are many ways to implement homing for missiles. Here's one that is commonly used in real life.

    Edit: I will not recommend using rb.addForce() because if u try it out u will realise it is too indeterministic.