I am currently creating a endless runner game in Space where the character will tilt to the direction they are going to. For instance, if the player presses “a”, which moves the character to the left, the character will look tilt to the left a bit. When the player stopped pressing “a” the character tilts back to its original position.
This is my code that I have created for both movements and tilting
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
public float upwardForce = 500f;
public float downwardForce = 500f;
public float tiltAmount = 15f; // Adjust the tilt amount as needed
private bool isTiltingW = false;
private bool isTiltingS = false;
void FixedUpdate()
{
// Ensure Rigidbody's rotation is not frozen
rb.freezeRotation = false;
// Apply forward force
rb.AddForce(transform.forward * forwardForce * Time.deltaTime);
// Apply sideways force based on user input
float horizontalInput = Input.GetAxis("Horizontal");
float horizontalForce = horizontalInput * sidewaysForce * Time.deltaTime;
rb.AddForce(transform.right * horizontalForce, ForceMode.VelocityChange);
// Tilt the player based on its velocity when "a" or "d" is pressed
if (isTiltingW)
{
float tilt = Mathf.Clamp(rb.velocity.y, -1f, 1f) * tiltAmount;
transform.localRotation = Quaternion.Euler(-tilt, 0, 0);
}
else if (isTiltingS)
{
float tilt = Mathf.Clamp(rb.velocity.y, -1f, 1f) * tiltAmount;
transform.localRotation = Quaternion.Euler(tilt, 0, 0);
}
else
{
// Smoothly return to the original rotation when not tilting
transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.identity, Time.deltaTime);
}
}
void Update()
{
// Detect if movement keys are pressed to enable tilt
isTiltingW = Input.GetKey("w");
isTiltingS = Input.GetKey("s");
}
}
When I ran the scene, the character starts moving backwards and whenever I press “a” “d” “s” or “w” it just starts flying all over the place with the camera too, the camera follows the player where I placed the main camera as a child of the character in the hierarchy. All I want is for the camera to not move, when the character moves to the direction the button is pressed (a is left d is right w is up and s is down) the character is tilted to that direction.
There must be some error in the code or it could be an error in my unity scene. I will be grateful if someone can help me with this issue.