Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

MoveTowards() / RotateTowards() problem

Discussion in 'Scripting' started by KasunL, Oct 7, 2021.

  1. KasunL

    KasunL

    Joined:
    Apr 19, 2015
    Posts:
    64
    Hi!

    So my Enemy craft throwing missiles at Player craft. I used MoveTowards() to make the missile "Guided", and it works. But the missile won't rotate towards the Player craft, so it looks a little glitchy. I tried calling both MoveTowads() and RotateTowards(), but then the missiles are not firing.

    Missle spawning and moving Code:
    Code (CSharp):
    1. if (timer > waitingTime)
    2.         {
    3.             enemyProj = GameObject.Instantiate(missilePrefab, projectileSpawnPoint.transform.position + new Vector3(0,0,-10f), Quaternion.Euler(0, 180, 0));
    4.             debrisDirection = new Vector3(Random.Range(-debDirOffsetx, debDirOffsetx), Random.Range(10, -debDirOffsety),
    5.                 Random.Range(100f, 200f));
    6.             astroRB = enemyProj.GetComponent<Rigidbody>();
    7.             astroRB.AddForce(debrisDirection * debrisSpeed, ForceMode.Impulse);
    8.  
    9.             txtMsg1.text = "";
    10.  
    11.             timer = 0;
    12.         }
    13.  
    14.         enemyProj.transform.position = Vector3.MoveTowards(enemyProj.transform.position, craft.transform.position, Time.fixedDeltaTime * 50);
    15.         //enemyProj.transform.position = Vector3.RotateTowards(enemyProj.transform.position, craft.transform.position, 1f, 0f);
    What I am doing wrong? Thanks!

    Current state:
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Use Quaternion.LookRotation to build a rotation towards your target (the docs have an example), then feed that value to the second parameter of Quaternion.RotateTowards.

    Your code is also mixing forces with manually moving the transform. You need to choose one or the other.
     
    KasunL likes this.
  3. KasunL

    KasunL

    Joined:
    Apr 19, 2015
    Posts:
    64
    Thanks, but RotateTowards() don't accept Quaternion. Any thoughts?
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    Are you using Vector3.RotateTowards() or Quaternion.RotateTowards()? Because as @GroZZleR suggest you should be using the latter.
     
    GroZZleR likes this.