简体   繁体   中英

HTML5 Canvas, How to show animated attacks between two points

I want to show attack animation between two points (source & target) on HTML5 canvas, similar to http://map.ipviking.com/

Below code making missile movement too slow at the end when distance remain short and does not seems real like a missile attack

velocityX = target.x - missile.shift.x;
velocityY = target.y - missile.shift.y;
missile.shift.x += velocityX * .001;
missile.shift.y += velocityY * .001;

Please help!

At row 1-2 you make the velocities depend on the distance between missile and target, shorter distance implies lower speed.

I guess what you seek is the direction, normalized, and then to choose the speed by yourself.

Let me show a simple example.

Target is at: [2, 3]
Missile is at: [4, 8]

Velocities (by your formula) are: [2, 5] (the diff on x and y separate) The "normalizationFactor" is calculated by the "pythagoras formulae":

var normalizationFactor= Math.sqrt(2*2 + 5*5);

To normalize, you need to shorten both velocityX and velocityY by normalizationFactor . After that, you can chose which number to like to choose your speed with. (you use 0.001 by now)

This is my attempt to patch your solution, haven't tested it, but you should get the idea:

velocityX = target.x - missile.shift.x;
velocityY = target.y - missile.shift.y;
var normalizationFactor= Math.sqrt(velocityX*velocityX + velocityY*velocityY);
var yourSpeed = 0.001;
missile.shift.x += yourSpeed * velocityX / normalizationFactor;
missile.shift.y += yourSpeed * velocityY / normalizationFactor;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM