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);
        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.

  • 2
    \$\begingroup\$ Try logging the angle, it should be between 0 and 6.28 \$\endgroup\$ – Bálint Oct 28 '16 at 6:48
  • \$\begingroup\$ 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. \$\endgroup\$ – Space Ostrich Oct 28 '16 at 7:08
  • \$\begingroup\$ 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. \$\endgroup\$ – Space Ostrich Oct 28 '16 at 7:14
  • \$\begingroup\$ DON'T EVER DELETE QUESTIONS It hurts both the community and you. \$\endgroup\$ – Bálint Oct 28 '16 at 7:51
  • \$\begingroup\$ 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. \$\endgroup\$ – 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);


So, based on your description, it seems like you have an angle issue.

I don't know about unity, but it seems like you get the angle in degrees instead of radians.

To hopefully solve your issue, before you pass the angle to the sin and cos function, convert it to radians with the following formula:

rad = deg / 180 * PI

Side note: I'm seriously curious why unity returns the angle in degrees, when radians are arguably more useful.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.