- Home /
How to set the player in front of the camera in any rotation
Hi, I make a game, but I don't know how to make it, that when a player falls from a higher place, the front side stays the same as the camera stands. (In this case, I use a rigid body.) Could use "freeze rotation", but I can't do that, because in this project everywhere except in this case it is necessary for the player to rotate. Sample-
I think it could be made that while a player falls from somewhere, it is allowed to rotate freely, but when it touches the ground, its front is set equal to the front of the camera.
The next problem could be, even if made so far, the player can touch the ground with a corner when he falls, or can't it be that the player sets the front until it isn't standing straight on the ground?
Code I use(there isn't camera movement)-
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rigg;
private Vector3 moveDirection;
public float speed;
void Start()
{
rigg = GetComponent<Rigidbody>();
}
void Update()
{
float hor = Input.GetAxisRaw("Horizontal");
float ver = Input.GetAxisRaw("Vertical");
moveDirection = transform.forward * ver + transform.right * hor;
rigg.AddForce(moveDirection.normalized * speed, ForceMode.Acceleration);
}
}
Thanks!
Answer by DenisIsDenis · May 27, 2021 at 10:53 AM
This code can help (assign to the player's script):
void OnCollisionStay(Collision collision)
{
Quaternion deltaRot = Quaternion.FromToRotation(transform.right, Camera.main.transform.right);
transform.rotation = Quaternion.Lerp(transform.rotation, deltaRot * transform.rotation, 10f * Time.deltaTime);
}
OnCollisionStay is really heavy, there should be another way to do it.
For optimization, you can use raycast:
float counter;
public float distanceToGround = 0.8f;
Quaternion deltaRot = Quaternion.identity;
void Update()
{
counter += Time.deltaTime;
Ray ray = new Ray(transform.position, -Vector3.up);
if (counter >= 0.25f) // check is performed 4 times per second
{
counter = 0;
if (Physics.Raycast(ray, out RaycastHit hit, distanceToGround))
{
deltaRot = Quaternion.FromToRotation(transform.right, Camera.main.transform.right);
}
}
transform.rotation = Quaternion.Lerp(transform.rotation, deltaRot * transform.rotation, 5f * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
How to make a player rotate in a direction with a slope of the ground. 0 Answers
Player rotates with camera(face same direction as the camera) 1 Answer
How to align an object's rotation to another GameObject's rotation (without parenting the Objects) 1 Answer
Euler makes my look script stop... 1 Answer