I am trying to develop a small java 2d tower defense game and I have run into problems trying to calculate how to do my missiles. After hours of searching and testing I am even more confused.
What I have so far is:
Math.sqrt(x2, x1, y2, y1)
. Now the problem I am running into is how to scale the incrementing x and y of the missile towards the target so it seems realistic. Math is not my strong suit and it is showing here. Below I have show what I have for the SE quadrant from the tower.
public int distanceX, distanceY;
public double sep, scale;
if(xBullet < Screen.mobs[shotMob].x && yBullet < Screen.mobs[shotMob].y){
distanceX = Screen.mobs[shotMob].x- xBullet;
distanceY = Screen.mobs[shotMob].y - yBullet;
sep = Math.sqrt( (distanceX * distanceX) + (distanceY * distanceY));
scale = // This is the part I am confused about.
xBullet += distanceX * scale;
yBullet += distanceY * scale;
If you want a fixed velocity, simply use:
scale = someConstant;
To move the bullet, you can use the direction vector you already found, but you have to normalize it by dividing by distance:
xBullet += (distanceX / sep) * scale;
yBullet += (distanceY / sep) * scale;
Basically you get the velocity unit vector with the direction you want to go, and you multiply it against speed to get the actual velocity vector. Your xBullet
and yBullet
fields should be floating pointing values (eg. doubles), not integers, though.
I'm going to make a Tower Defence today. I have thought about it and this is how I will shoot from my towers etc.
How to calc distance to target: Pythagorean theorem. x target - x tower for one length of it and y target - y tower for other length of it. Sqr both of them and, add them together and sqr root the number you get. Thats the disatance to target. Although it would need some other code to work properly (you might get lengths in negative values, so you would need to change to to positive again)
condition: if distance to target is less than attack range of tower: action: tower shoots response : create a bullet that has a target fixed on it
loop : compare x and y between target and missile and increase x or y accordingly.
action : missile x and y are same as target x and y response : deal damage to target and remove missile
I'm not sure to get your point..apologize. Anyway couldn't you just do something like..
xMissile += (xTarget-xOrigin)/numberOfSteps
yMissile += (yTarget-yOrigin)/numberOfSteps
that's just an easy way to get a point to destination through a segment in the given number of steps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With