- Home /
Question by
unity_5120bee · Dec 18, 2017 at 11:20 PM ·
c#gameobjectunity 2dplatformerprojectile
Projectile gets stuck at character's position (Unity2d)
I have an enemy sprite that is shooting out horizontal projectiles. My only problem is that after the enemy shoots their projectile, it travels up until the position along x wherever my character is currently standing.
Let's say my enemy is on a platform above me and I'm standing -100f along the x-axis away from the enemy. The enemy shoots their projectile, it travels for -100f along x and then gets stuck ("hovers") directly above my character sprite's head.
My code for the projectile is below (I've omitted extraneous variables that aren't affecting the motion of the projectile for simplicity's sake):
[SerializeField] GameObject player; // Gets player's current position
private Transform transform;
private Vector2 projectilePosition;
void Update(){
projectilePosition = transform.position;
if (player.transform.position.x < transform.position.x) // if my player sprite is standing to the left of my projectile generator
{
projectilePosition += new Vector2(10f, 0); // projectile flies from left to right
transform.position = projectilePosition;
}
else if (player.transform.position.x > transform.position.x) // if my player sprite is standing to the right of my projectile generator
{
projectilePosition -= new Vector2(10f, 0); // projectile flies from right to left
transform.position = projectilePosition;
}
}
Comment