- Home /
Having some troubles with making the player slide down a rail
I'm having a bit of troubles getting the right calculation on how to make a play grind down a rail.
In the game I'm making I have the player grind down a rail with his skateboard, the calculation seems right. I'm using y=mx+b
as the form to calculate the position of the line, and I'm using this piece of code to calculate the slope. m
in the formula:
slope = (pointB.position.y - pointA.position.y) / (pointB.position.x - pointA.position.x);
Now to make the player grind I have this piece of script:
Player.cs
private void Grind(RaycastHit2D[] hit)
{
var grindObject = hit.Where(x => x.collider.tag == "grindable").FirstOrDefault();
if (grindObject.collider != null)
{
grinding = true;
var wantedTransform = transform.position;
var grindScript = grindObject.collider.gameObject.GetComponent<Grind>();
wantedTransform.y = grindScript.GetYPosition(gameObject.transform.position.x);
if (transform.position.y > wantedTransform.y - 0.5f && transform.position.y < wantedTransform.y + 0.5f)
{
transform.position = wantedTransform; grinding = true;
}
else
grinding = false;
}
else
grinding = false;
}
And the whole grind script is basically this:
public class Grind : MonoBehaviour {
public Transform pointA;
public Transform pointB;
public float slope;
public void Start()
{
slope = (pointB.position.y - pointA.position.y) / (pointB.position.x - pointA.position.x);
Debug.Log(slope);
}
public float GetYPosition(float playerXPos)
{
return (slope * playerXPos) + (pointA.position.y - pointB.position.y);
}
}
This script works perfectly for the first rail, but if I make the rail any longer or rotate it a bit, it fails to work and it makes the player float above the rail.
(Both images are the player grinding, the animations are just not set up yet.)
Does somebody know what's going on and what I'm doing wrong?
Your answer
Follow this Question
Related Questions
Help with sliding down hills 1 Answer
Ramp for stairs causes player to slide down. 1 Answer
How can I make my FPS character slide down a angle. 0 Answers
3d ethan character can't walk up 20 Deg slope 0 Answers
raycast and trigonometry 2 Answers