- Home /
Player moving up and down hill at different speeds (vector projection)
Consider this a side view, like in a 2D platformer. In the diagram, the light blue line is the slope of the surface the player is standing on (so it's about 45 degrees). The green arrow is the surface normal of the slope. The dark blue arrow is the player's movement vector walking into the slope, and the red arrow is the resulting vector when the blue vector is projected onto the green vector. (so basically, the red arrow is the final vector that the player will move at on the slope). When he's walking up the slope, all is well and he moves at the appropriate speed, but when he's walking DOWN the slope, he continues to move at the slow speed.
//get the vector that the player is supposed to be moving in. Vector3 movement_vec = new Vector3(0.4f,0,0); //player moves to the right //project player movement onto the surface he's on Vector3 adjusted_movement_vec = Vector3.ProjectOnPlane (movement_vec,hitinfo.normal); //now move the player posvec = transform.position; posvec += adjusted_movement_vec; transform.position = posvec;
I do understand mathematically that this is how it's supposed to be, since the vector we're projecting (blue) onto the surface in both cases (uphill and downhill) is the same magnitude, just pointing in the opposite direction, but I'm trying to determine how one would go about making it so that the player would move faster when walking downhill (whether that be a different approach altogether in Unity, or some other mathematical approach). Thanks! :)
Answer by Steamc0re · Aug 18, 2017 at 02:19 AM
void FixedUpdate()
{
RaycastHit hit;
if (Physics.SphereCast(transform.position, .25f, Vector3.down, out hit, 3f))
{
slope = Vector3.Dot(transform.right, (Vector3.Cross(Vector3.up, hit.normal)));
}
}
this gives a slope value between -1 and 1 depending on if you are facing uphill or downhill. I use it as a multiplier to adjust move speed in my game
Answer by winxalex · Aug 28, 2018 at 05:31 PM
Problem is explained in this video
First you need to find slopeDirection (let assume that always points downhill), then to find how slope influence speed by that how moveDirection is different from slopeDirection. If is full opposite from the slopeDirection value is max negative -1 slope max decelerate your movement, and if is in direction of slope(you are going down) is 1, slope is accelerating your movement.
slopeDirection=Vector3.Cross(Vector3.up, Vector3.Cross(Vector3.up, hit.normal))
slope = Vector3.Dot(moveDirection, slopeDirection))
Your answer
Follow this Question
Related Questions
Limit object position which is moved by accelerometer 0 Answers
MoveTowards inside Coroutine 2 Answers
Smooth motion physics Playmaker 0 Answers
Convert WASD to local rotation 1 Answer