Wwwebber's Blog

Rectangle on top of line…rotated at any angle

Posted in Uncategorized by wwwebber on March 6, 2010

Just started a new game and i needed to have a character who could ‘walk’ on a line at any angle …even upside pic .

With a little trig it’s fairly easy to place a rectanguler movieclip on top of a line.

Here’s all the source code

Here’s the critical code

c1 and c2 are the endpoints of the line that you can drag around (demo)
hero is the name of my rectangular object
xOffset is how far hero should move (based off left right arrow keys). Each time the key is pressed we add or subtract from this number. So it represents a “cumulative” and current x value.

//calculate angle of line based on endpoints
var angle:Number = Math.atan2(c2.y - c1.y, c2.x - c1.x);
//rotation of MovieClips in Flash is in degrees...so convert
hero.rotation = angle * 180 / Math.PI;
//how far (dx) are we from first of the two points
var xFromOrigin:Number = xOffset - c1.x;
//just some trig here
var newY:Number = c1.y + xFromOrigin * Math.tan( angle);
//get new coordinates of hero

hero.x = xOffset + h * Math.sin(angle)
hero.y = newY - h * Math.cos(angle)

Comments Off on Rectangle on top of line…rotated at any angle