PDA

View Full Version : Problem with distance


jdeisenberg
02-11-2008, 04:22 PM
I have a world set up with the island/palmtree, a penguin, and a fish.

I want the penguin to be halfway between the tree and the fish (or very close to it), so I set up this loop:

penguin.move to palmtree
penguin.turn to face fish
while penguin.distance to fish != penguin.distance to palmtree
penguin.move 0.1 meter towards fish

Yes, I know that the penguin moves through the island. That doesn't bother me. What is worrisome is that the penguin moves all the way to the fish and starts bouncing back and forth. I am making some incredibly simple error, but for the life of me I cannot see what it is. The world is at http://evc-cit.info/alice/halfway.a2w

jdeisenberg
02-11-2008, 04:39 PM
Argh. Never mind; I figured it out by having the penguin "say" its distance from the fish and the tree.

Here's the problem: since they are never exactly equal, the penguin will keep moving until it is very near the fish. The next move takes the penguin to the other side of the fish, so it has to move back. They're never exactly equal.

The correct way to do it is:

penguin.moveto palmtree
penguin.turn to face fish
penguin.move (penguin.distance to fish / 2) towards fish

DickBaldwin
02-11-2008, 04:57 PM
Argh. Never mind; I figured it out by having the penguin "say" its distance from the fish and the tree.

Here's the problem: since they are never exactly equal, the penguin will keep moving until it is very near the fish. The next move takes the penguin to the other side of the fish, so it has to move back. They're never exactly equal.

The correct way to do it is:

penguin.moveto palmtree
penguin.turn to face fish
penguin.move (penguin.distance to fish / 2) towards fish

You might try storing the distance to move in a variable. Initialize that variable to half the distance to the fish. Go into a loop. During each iteration, make one move toward the fish moving the distance that is currently stored in the variable. Then replace the value in the variable by half the distance to the fish before starting another iteration of the loop.

Theoretically, the penguin would never get to the fish. Practically, however, you could allow it to get arbitrarily close before terminating the loop.

To keep the animation from being jerky, cause each move to start and end abruptly.

Dick Baldwin
Free Alice tutorials: http://www.dickbaldwin.com/tocalice.htm
Free programming tutorials: http://www.dickbaldwin.com/toc.htm