# What is wrong with this character slope math?

I'm making a sidescrolling platformer and have implemented some code that should convert the characters speed to an X speed and Y speed based on the angle of the surface they are on. This actual math for this was taken from a web page and I don't know if it's right or not.

// xSpeed and ySpeed are derived from speed, based on the angle
xSpeed = speed * Mathf.Cos(angle);
ySpeed = (speed * -Mathf.Sin (angle)) - gravity;


The angle is found with this code:

RaycastHit ground;
Physics.Raycast (transform.position, Vector3.down, out ground, 1.5f);
Debug.DrawRay (transform.position, Vector3.down.normalized, Color.green, 2, false);
if (ground.collider != null)
{
angle = Vector3.Angle (ground.normal, Vector3.up);
}
else
{
angle = 0;
}


This works fine when walking on a flat surface, but freaks out when walking on a slope. I believe the problem lies with the angle itself.

• Try logging the angle, it should be between 0 and 6.28 – Bálint Oct 28 '16 at 6:48
• I have been, it's 0 on the flat, and seemed to be the inverse of what it should have been when I went on a slope. I was getting roughly 10 back when standing on a slope that I eyeballed at being -10 degrees. – Space Ostrich Oct 28 '16 at 7:08
• I'll leave it up for a little in case anybody objects, but as I've decided I'm not getting any benefits out of this kind of angle code and it adds a bunch of complexity, I'm going to delete the question. I'll be switching to simpler movement as it better matches the design. – Space Ostrich Oct 28 '16 at 7:14
• DON'T EVER DELETE QUESTIONS It hurts both the community and you. – Bálint Oct 28 '16 at 7:51
• Also, this is not complex. If you want to develop games, you need math. And this is just the tip of the iceberg. You'll even need linear algebra, which is far more complicated. – Bálint Oct 28 '16 at 7:52

I think you want to get the angle between the horizontal "default" ground and the line formed by the surface of the slope. So I think the angle = Vector3.Angle (ground.normal, Vector3.up); should be changed to angle = Vector3.Angle (ground.normal, Vector3.right);
rad = deg / 180 * PI