- Home /
Velocity direction help
Hi all,
I have a part of my enemy script causing problem and cant seem to find a solution
my enemy instantiates a projectile towards Player when Player in range. No problem here of course.
The problem is the instantiated projectile does not go towards me, but always shoots in a wrong direction. I tried with transformDirection & InverseTransformDirection, but none seem to work.
am I doing something wrong? here is this part of code:
Rigidbody instantiatedProjectile = Instantiate(projectile, spawnPoint.transform.position, spawnPoint.transform.rotation) as Rigidbody;
goToPlayer = instantiatedProjectile.transform.InverseTransformDirection(Player.transform.position);
instantiatedProjectile.velocity = goToPlayer * 1 * Time.deltaTime;
Thanks for any help possible
Answer by robertbu · Sep 01, 2013 at 03:16 PM
TransformDirection() and InverseTransformDirection() translate between local and world coordinates. Everything in this problem is already in world coordinates. Planer.transform.position is a world position relative to the origin. What you want is a vector from the projectile to your target. You need to normalize it, so that the distance to the player does not effect the velocity. Also for a one-time application of velocity, you don't want/need to use Time.deltaTime:
goToPlayer = (Player.transform.position - spawnPoint.transform.position).normalized;
instantiatedProjectile.velocity = goToPlayer * speed;
great thanks for quick advice! tried to do something like this, but did not know about 'normalized'
Converted my previous answer into a comment to help explain @Robertbu's answer further.
You do not need to use InverseTransformDirection. You are computing your direction vector wrong. In psuedocode, this is what you need to do:
To get your direction, just: Direction = PlayerPosition - EnemyPosition
Normalize the direction: NormalizedDirection = Direction.Normalize();
Projectile.velocity = NormalizedDirection.