Im hopelessly not good at algebra and such. But im trying to learn. I want to learn and understand how to use it in game programming rather than modifying snippets or using classes that do it for me.
So what i want to start with is to click on location and have an object move there. This is what i am thinking (in pseudocode and in a 2D world).
vector2 mousePosition;
vector2 playerPosition;
vector2 direction = playerPosition - mousePosition;
direction.normalize; //ive learned that this should be done, and i understand what it means to normalise a vector, but i am not quite sure of what goes wrong if the vector is not normalised
//in the players update
if (player is not facing destinations direction)
{
player.transform.direction = Lerp towards direction;
}else if(player IS facing the destinations direction)
{
player.rigidbody.AddForce(vector.forward, 100f);
}
Am i thinking correctly?
Answer
It depends on how you want your character to behave. In general, what you wrote is approximately correct, but be careful of a few things:
- If the player is already at the
mousePosition
, then direction will have zero length and normalize will be a division by zero! To prevent this, just have an if statement and don't continue unlessdirection.length > 0.01
(or some other small constant). - Similarly, be careful with the directions. The test
player is not facing destinations direction
is as simple asdirection * player.transform.direction < 0.95
, where * is the dot product, assuming both directions are normalized (this is why you want to normalize). Basically, as two unit-length vectors (i.e. directions) get nearer to each other, their dot product gets closer and closer to 1, and if they are the same, then their dot product is exactly 1. On computer of course, the is rounding error, which is why you choose a cut-off close to, but not exactly, 1. - Finally, I'm not sure what system you are using, but adding a force is almost certainly the wrong way to get something like a character to move realistically, because players rarely have significant inertia, except in space sims. Also, you probably want to use the target direction rather than vector.forward.
- See http://www.red3d.com/cwr/steer/Arrival.html, and the other behaviours on that site to get an idea of how to control characters which need to slow down/speed up. If your character is a person/creature, these are not what you are looking for, as you need something designed for a character which can start and stop on a dime.
No comments:
Post a Comment