# Shooting object in a direction of another object

Hi,

I want to move an Object (a bullet) to the direction/position of my current Player, the bullet is shot from an Enemy object, currently i can just get it to shoot down (which is ok because my Player is down, but i want it to the be on the correct X of the player)

Been looking a lot in the forums, and i’ve tried everything i could find but i guess i’m missing something stupid, because i just cant get it to work!

This is my current code:

``````GameObject enemyBullet= Instantiate(enemyBulletPrefab, transform.position, Quaternion.identity) as GameObject;
enemyBullet.GetComponent<Rigidbody2D>().velocity = new Vector2(FindObjectOfType<Player>().transform.position.x, -20f);
``````

I’ve tried AddForce (i have a rigidbody) , i’ve tried a lot of things, i just cant get it to settle it on the player’s x correctly.

Just to clarify - the Enemy is up, the Player is down, the shooting only goes from the Enemy downwards to the Player…

up

Vector subtraction will give you a result that is the direction from one position to another. If you want a vector pointing from point B to point A, you can get it by subtracting B from A:

In code it would look something like this:

``````Vector2 playerPosition = /* Get player position here */;
Vector2 enemyPosition = /* Get enemy position here */;
Vector2 fromEnemyToPlayer = playerPosition - enemyPosition;

// Normalize it to length 1
fromEnemyToPlayer.Normalize();

// Set the speed to whatever you want:
Vector2 velocity = fromEnemyToPlayer * ProjectileSpeed;

// Set the rigidbody velocity
myRigidbody.velocity = velocity;
``````

Hi,

I’ve tried something like that in my experiments but i didnt use “Normalize”, just did some reading on what it is.

Thank you very very much!!!