Spawning bullet and changing direction to touched position

Hello all I’m fairly new to coding and need some guidance. Taking the example from the invaders game the bulllet spawns and move forward. Ive been stuck and been trying to get the bullets to move to where CurrentTouched.x and y are. I have managed to make a marker to follow where I am touching but having trouble with the bullets. If anybody can help that would be most appreciated

heya, not tested, but this should work:

edit: you need to select the proper images for this to work of course


function setup()
 speed = 10
 bullet = vec2(WIDTH, HEIGHT)
 target = vec2(0, 0)
 bulletImage = readImage("somepicture")
 targetImage = readImage("somepicture")
end

function draw()
 background(0)
 target.x = CurrentTouch.x
 target.y = CurrentTouch.y

 local dir = math.atan2(target.y - bullet.y, target.x - bullet.x)
 bullet.x = bullet.x + math.cos(dir)*speed
 bullet.y = bullet.y + math.sin(dir)*speed

 sprite(bulletImage, bullet.x, bullet.y)
 sprite(targetImage, target.x, target.y)
end

edit2: note that you can change the rotation of the bullet using that same “dir” value

Cheers

edit: well i’m tired, watching SC2 at the same time… After re-reading your post, it seems you already got that working ?
Or do you mean you got a sprite to draw at your current position. If that’s the case, the above code makes a “bullet” follow your finger

Else, I’ll let someone else look into the invader code and answer you, since I don’t have my iPad available atm ^^

Ty so much that really helped a lot i got a lot more work done again

.@Fluffmeister - have a look at http://codeatuts.blogspot.com.au/2012/08/tutorial-14-spacewar-extended-ship-class.html

There may be some code there that you can re-use.

It should be better to use vec2 functions such as vec:rotate() and vec:angleBetween() isn’t it?
I think it makes the code clearer.

Well yes you can use vectors, although I’m not sure it would be “clearer” in this case. I showed the trig because it’s useful math to know and understand.

The “cleaner” way would be to replace the middle 3 lines with


bullet = bullet - speed*(bullet-target)/bullet:dist(target)

What would be better for sure though, is to add more of that precious time it took you to state there are better ways that the one I presented, and actually show the OP some code :wink:

Cheers