HTML and CSS Reference
In-Depth Information
To find the actual target, you need to first find the angle between the object and the fixed point, and then
move out from the fixed point at that angle—the length of the spring. In other words, if the length of the
spring were 50, and the angle between the ball and fixed point were 45, you would move out 50 pixels
from the fixed point, at an angle of 45 degrees, and that would be the ball's target to spring to. Figure 8-5
illustrates how this works.
Fixed point
x distance
Angle
Spring
length
Spring target
y distance
Figure 8-5. Offsetting a spring
The code to find the target in this case would be:
var dx = ball.x - fixedX,
dy = ball.y - fixedY,
angle = Math.atan2(dy, dx),
targetX = fixedX + Math.cos(angle) * springLength,
targetY = fixedY + Math.sin(angle) * springLength;
The result is that the object will spring toward the fixed point, but will come to rest some distance away
from it. Although we're calling it a “fixed point,” this just means the point to which the spring is fixed, it
doesn't mean that point cannot move. Perhaps it's better just to see it in action. You'll go back to using the
mouse position, but this time, it will be the spring's fixed point. The spring's length will be 100 pixels.
Here's the example (document 13-offset-spring.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Offset Spring</title>
<link rel="stylesheet" href="style.css">
</head>
Search WWH ::




Custom Search