Question

I have this moving character and when I press a button I want it to shoot at a object pointed by the mouse. But the character is moving so I don't know how to make the animation in a specific place. I am using Flash, actionscript 2 or 3

Was it helpful?

Solution

There are many ways in which it can be done, but this one is known to be one of the simplest:

Given source point A and target point B:

Calculate distance between A and B

var distance:Number = computeDistance(A,B); //define your function where computeDistance returns the Pythagorean distance between A and B

Calculate x and y difference

var dx:Number = B.x - A.x;
var dy:Number = B.y - A.y;    

// normalization. Think of this as a ratio of the legs relative to the hypotenuse
dx = dx / distance; 
dy = dy / distance;`

Calcualate xSpeed and ySpeed by multiplying dx and dy with speedPerFrame (arbitrary)

var xSpeed:Number = dx*speedPerFrame;
var ySpeed:Number = dy*speedPerFrame;

Increment your object's x and y position using xSpeed and ySpeed in the main game loop (respectively). Make sure you add a check if the object has arrived at the destination point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top