Problem: Shoot bullet in direction of player C#
I'm doing a 2D platformer game where the enemy should shoot to the player. My problem is, that the bullets always fly in the right direction, even if the enemy is looking to the left side(if the player is at the right side of the enemy, the shooting works perfect). The bullet spawn at the left side, but tries to change his direction to the right. Example: at the blue points the bullets spawn, but like you can see in the picture below, the bullets fly to the right direction. Script for the direction:
public class EnemyShoot : MonoBehaviour {
float speed;
Vector2 myDirection;
bool isReady;
void Awake(){
speed = 5f;
isReady = false;
}
void Start () {
}
public void SetDirection(Vector2 direction) {
myDirection = direction.normalized;
isReady = true;
}
void Update () {
if (isReady) {
Vector2 position = transform.position;
position += myDirection * speed * Time.deltaTime;
transform.position = position;
}
}
}
Method, where the bullet get shot:
void FireEnemyBullet()
{
GameObject player = GameObject.Find ("Player");
if(player != null)
{
GameObject bullet = (GameObject)Instantiate(waterball);
bullet.transform.position = transform.position;
Vector2 direction = player.transform.position - bullet.transform.position;
bullet.GetComponent<EnemyShoot>().SetDirection(direction);
}
}
@Serdan 's comment right. player-bullet will give you the correct direction (+1)
Read the question again. It's about the enemy shooting the player.
Heretsu gets a direction vector by subtracting bullet position from player position. There's nothing wrong with that. In fact, I can't see anything wrong with the code as posted and certainly nothing that would explain the curved path.
@Heretsu, try standard debugging procedure: Simplify until it does what you would expect.
(Btw, GameObject.Find() is expensive, you should use a permanent reference.)
@Serdan you are right, I misread the question, so my answer is not relevant and I'll just edit it and convert it to a comment.
Edit: Serdan is right, the direction should be player-bullet.
What values are you using to deter$$anonymous$$e direction? For instance, what do you get when you add the following to line 9 of FireEnemyBullet?
Debug.Log("Player: "+player.transform.position+" Bullet: "+bullet.transform.position);
a-b will get you a direction vector from b to a.
So player-bullet will get you a direction from bullet to player, which is what you want in this scenario.
Answer by Heretsu · Sep 14, 2015 at 11:03 AM
Thanks for your answers, I fixed the problem. I dont know how exactly, but I played arround with the scripts and it worked. At first I changed myDirection = direction.normalized; to myDirection = direction;
and it worked for me, but if I change the code back to the origin, it still works like it should. Maybe the script had some problem with a other script that was attached to the object.