I am making a simple shooter game for Android where the player is a human and is being attacked by aliens. How would I make a laser beam, so that when the user touches the screen or presses the trackball the laser just fires in a straight line?
|
Just yesterday someone asked almost exactly the same question over on stackoverlow.com. I'm going to quote my answer from there and edit it a little to fit your post: http://stackoverflow.com/questions/6300169/moving-objects-help/6300303#6300303 I don't know what kind of library you're using to draw all of your things, but that basically doesn't matter since you only need to know two things in order to do this: You'll probably want to set up a vector class in order to deal with these kinds of things more comfortably. I'm going to assume that you already have one. In case you don't know about vector math, there's this very useful tag page on here with links to two excellent articles on the topic: http://gamedev.stackexchange.com/tags/vector/info You need to calculate the direction that the beam moves in depending on the touch's position. You get this direction by simply subtracting the position of the touch from the position of the player:
In order to just get a direction instead of adding a velocity component to this vector, you need to normalize it (so it has a length of 1):
The normalize code inside Vector 2 would look something like this:
And the length code like this:
You then need to update the beam position by adding the product of the direction and the speed that you want the beam to travel with.
If you have some way of measuring the time between two frames, the speed variable should depend on the elapsed time between those frames, in order to create smooth movements on different platforms. Then, the code would simply add another multiplication:
|
|||||||||||||||||
|
newposition=oldposition+deltatime*(target - oldposition)/length(target - oldposition) * speed. and you just have to check each cycle if that object hit anything or not. – Gajoo Jun 11 '11 at 19:33