# Creating Projectiles (Beam)

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?

-
when something moves in a straight line it's called a beam, not a projectile! – Ali.S Jun 11 '11 at 19:04
I made an edit to say beam except title part. – MarkEz Jun 11 '11 at 19:16
I can't get where the real problem is, you just need to locate target (for example where the screen is touched) and move some object from player to that target in a straight line. it's only a simple vector2D equation : newposition=oldposition+deltatime*(target - oldposition)/length(target - oldposition) * speed. and you just have to check each cycle if that object hit anything or not. – Ali.S Jun 11 '11 at 19:33
If they touch the screen its not going to where they touched, its going straight from the players position. – MarkEz Jun 11 '11 at 19:44
A projectile, I was told by the first comment that what I was asking for was a beam but it starts at the player and ends when it hits a alien. It's not a continuous object, you touch and it shoots out and stops when it collides. – MarkEz Jun 12 '11 at 19:54

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:

Vector2 direction = Vector2.subtract(touchPosition,playerPosition);

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):

direction.normalize()

The normalize code inside Vector 2 would look something like this:

public void normalize()
{
float length = this.length();
this.x /= length;
this.y /= length;
}

And the length code like this:

public void length()
{
return math.sqrt(this.x*this.x + this.y*this.y);
}

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.