So it’s been a while since I’ve posted, so I thought I would post something that was both useful and nostalgic. I haven’t had a need to do any form of trig since college, maybe even high school. But for the hackathon last week, I was building an in-browser version of Missile Command that let you blow up the contents of the page. To do this, I needed to animate missiles being fired and I need to know what the angle between the base and the target to rotate the missile sprite to look correctly. So my first search yielded the following code snippet:
var angle = Math.atan2(y2 - y1, x2 - x1);
This seemed pretty simple and straightforward and to get the x2 and y2 values, I used the clientX and clientY values from the mouse click event and I used getBoundingClientRect() to get the top and left properties of the base which was a div element positioned at the bottom of the page. So the final code to calculate the angle looked like this:
// e - mouse event // base - div element var baseRect = base.getBoundingCLientRect(), y2 = e.clientY, x2 = e.clientX, y1 = baseRect.top, x1 = baseRect.left + (baseRect.width/2), angle = Math.atan2(y2 - y1, x2 - x1);
So this made perfect sense and I was feeling pretty good (except for the flashbacks to high school and sitting in those uncomfortable chairs hoping the teacher wouldn’t notice I didn’t do my homework). I then use the CSS Transform property to rotate my missile sprite like this:
transform:rotate(angle); -ms-transform:rotate(angle); /* IE 9 */ -webkit-transform:rotate(angle); /* Opera, Chrome, and Safari */
And of course this is going to work on my first try, right? If you’ve read any of my other blog posts, you should know by now that nothing I do ever works on the first try. So I click in the upper-right quadrant of the page and the missile rotates to point straight up. At first, I think it’s because my sprite is actually pointing up and I need to offset the rotation. Then I think there’s something wrong with how I was calculating the x and y coordinates. So I debug all the values and they look okay. Then I look at the calculated angle value and notice that it’s not even close to what it should be. What could I have done wrong… that’s when I went back to the original equation and realized that angle was returned in radian and not degrees. Well, first I had to remember what radians were and then I had to figure out how to convert it into degrees which turned out to be pretty simple:
var angleDegrees = angleRads * (180/Math.PI);
And then we go, now we have an angle in degrees that works. Like I said at the beginning, this was a useful exercise in using something I learned in school and something that felt somewhat nostalgic. Since I want to do more game development, I have a feeling this is only the beginning of my adventures of trying to remember trig basics. Wish me luck…