Image a object that moves automatically in one direction with a speed, let’s call it “direction x” and “speed x”.
Additionally the player can move the object with arrow-keys and look around. So, he can apply a force in every direction, a first person controller. Here comes the problem:
The player could press the key that “looks” at the direction x and his speed would grow.
“speed x” + added speed by player > “speed x”
I look for a methode that prevents this addition of speeds in this direction. The player shouldn’t be able to accelerate along the direction x.
Ok, just limit the global speed of the object and the job is done? I don’t think so. When the player would move sideways relatively to the predefined “direction x”, his speed has to grow (a² = b² + c²), he should make a curve at the end. When I just limit the global speed of the object I would need to crop the “speed x” and decrease it, because I need a “free speed” which the object has to use to make the curve. But that’s not good! So, the speed of the object can grow but not in the “direction x”. I hope you can understand what I mean!
What you think?
i had a similar problem when i was trying to implement jumping for my 1st-person controller. what i did was simply subtracting the current input direction from the current speed as soon as i jumped, so if the player keeps holding down those buttons he will have the same speed as before, but if he releases the button he actually gets slower in the air.
pseudo-code:
if(startJumping) then
speed x -= inputDirection
…
Move(speed x + inputDirection)
Thank you for the your approach!
In the meantime, while thinking about it, I have found another way of doing it.
I have to detect the excessive speed and crop it down to the normal speed value with tan(), cos() and sin() functions, a bit tricky but it works I guess, not finished yet.
I may put the final code in the wiki somewhere afterwards =)
It’s in pseudo Math but:
Vector2 newDirNorm = newDir.normalized;//The direction you are pressing
Vector2 speedNorm = speed.normalized;//The speed you want him to always use.
float ratio = Math.Dot(speedNorm, newDir);//The difference between the angles (1 if parralel, 0 if perpendicular(should do something to make sure ratio never goes below 0.
newSpeed = newDir + ((1 - ratio) * speed);//Adds any lost velocity in the desired direction back onto the direction you want to go.
That’s done off the top of my head, but I think experimenting with the Dot product could get you a much simpler function.
This one instead of limiting your speed, it just makes up any lost speed, so it implies that your button press max is the same as your original speed.