Tried nearly everything I found on Unity Answers and Yotube and still haven’t found a solution, it’s been a week and I’m freaking out! Really need some help on this one…
I have a cube with the script below attached, and I want its rotation to change towards where it’s moving (if I move back, I want the “front” of the cube to turn back).
public class PlayerMovement : MonoBehaviour {
public CharacterController charController;
public Transform CameraTransform;
public float speed = 8.0f;
public float gravity = 9.8f;
public float jump = 10.0f;
bool canJump;
bool onWall;
float verticalVelocity;
Vector3 velocity;
Vector3 wallBounce;
Vector3 normal;
void Update () {
Vector3 movement = Vector3.zero;
movement.x = Input.GetAxisRaw ("Horizontal");
movement.z = Input.GetAxisRaw ("Vertical");
movement = Vector3.ClampMagnitude (movement, 1f);
movement *= speed;
Quaternion movementRotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(CameraTransform.forward, Vector3.up), Vector3.up);
movement = movementRotation * movement;
movement = transform.TransformDirection (movement);
if (charController.isGrounded == false) {
movement = wallBounce;
}
movement = Vector3.ClampMagnitude (movement, speed);
movement = movement * (Time.deltaTime / Time.timeScale);
verticalVelocity = verticalVelocity - gravity * (Time.deltaTime / Time.timeScale);
if (Input.GetButtonDown ("Jump")) {
if (onWall)
{
Vector3 projected = Vector3.ProjectOnPlane (normal, Vector3.up);
wallBounce = projected.normalized * speed;
}
if (canJump)
verticalVelocity += jump;
}
movement.y = verticalVelocity * (Time.deltaTime / Time.timeScale);
CollisionFlags flags = charController.Move (movement);
velocity = movement / (Time.deltaTime / Time.timeScale);
if ((flags & CollisionFlags.Above) != 0)
{
canJump = false;
onWall = false;
movement.y = 0 * (Time.deltaTime / Time.timeScale);
}
if ((flags & CollisionFlags.Below) != 0)
{
wallBounce = Vector3.ProjectOnPlane (velocity, Vector3.up);
canJump = true;
verticalVelocity = -5f;
onWall = false;
}
else if ((flags & CollisionFlags.Sides) != 0)
{
canJump = true;
onWall = true;
}
else
{
canJump = false;
onWall = false;
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
normal = hit.normal;
}
}
I will suck your soul out through your wee wee if you solve this one for me, thanks.