I wanted my player to be moved along the normal of my floor object. Something like this:
I don’t want the movement to be straight all the time, as it is noticeable when going down slopes. I also want the player to jump perpendicular to the floor at all times. I also tried to implement a quick and dirty speed limiter to make sure it does not go too fast.
The code I have currently does the perpendicular jumping fine, but the left-right movement is a bit messed up. Also, I am currently controlling the player with the rigidbody component.
void Update()
{
if (active)
{
Vector2 velocity = Vector2.zero;
Vector2 sideVelocity = Vector2.zero;
Vector2 jumpVelocity = Vector2.zero;
Vector3 sub = new Vector3(0, 1, 0);
if (Input.GetKeyDown(KeyCode.W))
{
if (grounded)
{
Vector2 jumpVector = new Vector2(0, jump);
Vector2 normal = Vector2.zero;
RaycastHit2D hit = Physics2D.Raycast(transform.position-sub,-Vector2.up);
if (hit.collider != null)
{
Debug.Log( "name of raycast collider: "+ hit.collider.name);
Quaternion rot = hit.collider.transform.rotation;
normal = hit.normal;
normal.Normalize();
jumpVelocity = rot*jumpVector;
//velocity = jumpVelocity;
Debug.Log("velocity: " + rot * jumpVector);
}
}
else
{
jumpVelocity = Vector2.zero;
}
}
//Left Right Movement
if (Input.GetKey(KeyCode.A))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position - sub, -Vector2.up);
if (hit.collider != null && grounded)
{
Debug.Log("name of raycast collider: " + hit.collider.name);
Quaternion rot = hit.collider.transform.rotation;
sideVelocity = rot*-speedVector;
}
else
{
sideVelocity = speedVector;
}
}
if (Input.GetKey(KeyCode.D))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position - sub, -Vector2.up);
if (hit.collider != null && grounded)
{
Debug.Log("name of raycast collider: " + hit.collider.name);
Quaternion rot = hit.collider.transform.rotation;
sideVelocity = rot * speedVector;
}
else
{
sideVelocity = speedVector;
}
}
velocity = sideVelocity + rb.velocity;
if (velocity.x > maxXSpeed)
{
velocity.x = maxXSpeed;
}
if (velocity.x < -maxXSpeed)
{
velocity.x = -maxXSpeed;
}
if (velocity.y > maxYSpeed)
{
velocity.y = maxYSpeed;
}
if (velocity.y < -maxYSpeed)
{
velocity.y = -maxYSpeed;
}
rb.velocity = velocity;
}
}
thanks for the help!