MoveTowards always using (0,0) as current (starting) vector

I’m new to C# and Unity, and while I’m only on the laser defender project I am attempting to learn how to implement different features. Currently, I have an enemy prefab that has a child Circle Collider 2D (trigger) which results in the enemy firing as long as the Player is touching it.

The enemy (helicopter) rotates and I’m attempting to have the instantiated projectiles fire only towards the center of the circle collider. (In-game, this appears as though the Player has been “seen” by the helicopter, resulting in being fired upon.) The goal is to have the direction of fire be tied to the position and rotation of the helicopter/child collider.

So far I’ve been successful in everything but getting the projectiles to fire in the direction of the child collider. I’m using MoveTowards to get the correct vector it should follow, however after a good bit of testing and reworking, I’ve found that using MoveTowards always uses (0,0) as the current (or starting) vector, almost as if it’s using transform.localPosition rather than transform.position. This results in the projectiles always following the exact vector from (0,0) to the world position of the collider (or target.)

This is the current state of the firing coroutine (bear in mind, I’m still very new to this so it’s not the prettiest):

    IEnumerator FireProjectile()
    {
        
        var projectileMovement = projectileSpeed * Time.deltaTime;
        var chopperRotation = transform.rotation;
        
        GameObject enemyShot = Instantiate(
                weaponFX, transform.position,
                chopperRotation) as GameObject;

        var target = chopperTarget.transform.position;

        enemyShot.GetComponent<Rigidbody2D>().velocity = Vector2.MoveTowards(transform.position, target, projectileMovement);

        Destroy(enemyShot, 1f);
        
        yield return new WaitForSeconds(shotTimer);
    }

Is there a much simpler way to do this, or is there something glaring that I’m missing? Should MoveTowards not be used at all for this type of situation? Any feedback is much appreciated, thanks!

Edit: For visual reference, this is the result of the above code. Note that the circle collider (or target) is in the spotlight that the car (Player) is touching:

Yeah I was definitely barking up the wrong tree with MoveTowards >_<

Turns out all I had to do was make a vector2 variable assigned to the difference between the target position and the projectile position.

Does that mean you fixed the issue? :slight_smile:

Aye :]

Fantastic. :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms