HTML and CSS Reference
In-Depth Information
moveBall();
target = reach(segments[0], ball.x, ball.y);
segments.forEach(move);
checkHit();
segments.forEach(draw);
ball.draw(context);
}());
The collision detection is executed after the motion code, so everything is in its final position. Here's the
start of the checkHit function:
function checkHit () {
var segment = segments[0],
dx = segment.getPin().x - ball.x,
dy = segment.getPin().y - ball.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < ball.radius) {
//reaction goes here
}
}
The first thing you do is determine the distance from the end pin of the first arm to the ball, and use
distance-based collision detection to see whether it hits the ball.
Now you need to do something when you detect a hit. For this example, the arm throws the ball up in the
air (negative y velocity) and moves it randomly on the x axis (random x velocity), like so:
function checkHit () {
var segment = segments[0],
dx = segment.getPin().x - ball.x,
dy = segment.getPin().y - ball.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < ball.radius) {
ball.vx += Math.random() * 2 - 1;
ball.vy -= 1;
}
}
This works out pretty well, and the final code can be found in 07-play-ball.html . If the arm happens to
lose its ball, don't be sad, you can always refresh your browser to keep playing. But this example is just
that, an example. You might want to use this technique to have the arm catch the ball and throw it toward
a target, or play catch with another arm. Try different reactions, because you certainly know enough now
to do some interesting things.
Using the Standard Inverse Kinematics Method
The method we describe for inverse kinematics is relatively easy to understand and program, doesn't
require a lot of system resources to process, and most importantly, works. But there is a more standard,
 
Search WWH ::




Custom Search