how to make enemy shoot projectile at right and left direction

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By amaou310

Im trying to make 2d enemy who will shoot toward right and left direction once player entered PlayerDetector area. I know how to instanciate projectile and make it move, but I have no idea how to write a code to set a direction.

:bust_in_silhouette: Reply From: Gazi Safin

just store the direction the enemy is moving at like this

dir = velocity.x/abs(velocity.x)
the abs return the positive value like |velocity.x|

the dir will then be either +1 or -1

and when instancing, remember to store the instance in a temp var so the properties can be changed.
var temp = bullet.instance() owner.add_child(temp)

now you can access the properties of the bullet and be like

temp.position = pos temp.velocity.x *= dir

the bullet needs to have something like:
position.x += speed *velocity.x

This is a lazy way to make it work and there are many other ways to do it though.

Oh sorry to mention but enemy does not move. and bullet is kinematicbody2d.
bullet.direction = Vector2.Right kind of worked but not Left.

amaou310 | 2023-04-24 06:26

Then try

b.velocity = Vector2.RIGHT    
if Player.position.x < Enemy.position.x:
   b.velocity = Vector2.LEFT

or add two areas. that way, u may control if the player is too close that if it’s under the eye line where the enemy shouldn’t see it, it would stop shooting. It isn’t needed though as the same effect can be gained by adding two collision shapes to the same area with the code above. I am late to reply but hope this helps in case.

Gazi Safin | 2023-05-08 09:06