CHARACTER ROTATION depending on camera IN UNITY - unity3d

I'm making a 3rd person controller in unity and i'm stuck: i can't figure out how to make the player follow my freelook cinemachine.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public GameObject Hoverboard_script;
public GameObject cinemachine_Hoverboard;
public Transform main_cam_tf;
void Update()
{
Hoverboard_script.SetActive(false);
cinemachine_Hoverboard.SetActive(false);
PlayerMovement_void();
CamController_void();
}
void PlayerMovement_void()
{
float hor = Input.GetAxisRaw("Horizontal");
float ver = Input.GetAxisRaw("Vertical");
Vector3 playerMovement = new Vector3(hor, 0f, ver).normalized * speed * Time.deltaTime;
transform.Translate(playerMovement, Space.Self);
}
void CamController_void()
{
float MouseY = main_cam_tf.eulerAngles.y;
Debug.Log(MouseY);
Quaternion rotation = Quaternion.Euler(0f, MouseY, 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * 4f);
}
}
Right now if i rotate the camera, the player enters a non-stop loop where it rotate constantly. How can i solve? Thanks, cheers

If you want to rotate the player as the rotation value of Y of Camera then remove all the lines of codes in which they rotate your object. Instead use one of these:
1.
transform.rotation = Quaternion.AngleAxis(Camera.Main.transform.eulerAngles.y, Vector3.up);
transform.rotation = Quaternion.EulerAngles(transform.eulerAngles.x, Camera.Main.transform.eulerAngles.y, transform.eulerAngles.z);

Related

Unity 3D Movement Problem when moving backward, if statement not the issue

This script in Unity allows me to move my player forward, left and right but not backwards. This script also allows me to turn the player and move in the direction of the camera.
However, When pressing the back arrow the player spins and moves randomly.
I tried removing the "if" statement, didn't help.
Totally stuck, please help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovment : MonoBehaviour
{
public Transform cam;
public float speed = 6f;
public CharacterController controller;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void FixedUpdate()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0f, verticalInput).normalized;
if (movementDirection.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(movementDirection.x, movementDirection.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f,angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}

Quaternion.lerp and position are being weird

So, I'm trying to have the camera follow the player (a car) and rotate with the player (... a car). However, it seems that either the quaternion.lerp is sus, or the positioning is. I've tried localPosition, but it doesn't really have an effect. It's rotating with the player, but it stays like... on one side of the player. Here is what I mean:
https://imgur.com/a/TQJOQ2X
and then
https://imgur.com/a/4FKm709
here's the code:
public class CameraMove : MonoBehaviour
{
[Header("References")]
[SerializeField] Transform player;
[Header("Attributes")]
[SerializeField] float camDelayIntensity = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.localPosition = player.position + new Vector3(0, 3, -8);
Quaternion endPos = Quaternion.LookRotation(player.forward);
transform.rotation = Quaternion.Lerp(transform.rotation, endPos, camDelayIntensity);
}
}

Rotate Camera vector to look at player Unity

I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)

How do i make my character move in the direction of the camera (Unity)

In Unity I want to make it so that when I hold w, instead of going in a single direction I want it to go forward in the direction of my camera how do I do that? (Sorry I'm new to unity)
EDIT: The movement script is:
using UnityEngine;
using System.Collections;
public class Player_Movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
As indicated by #lockstock, the direction the camera is facing can be retrieved from its transform. Here is an example below if you want to know how to use it.
public class Player_Movement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
// Drag & Drop the camera in this field, in the inspector
public Transform cameraTransform ;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = cameraTransform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
This scripts works without any error. I've tested it in Unity myself.
The forward direction of the camera is obtained by using Camera.main.transform.forward
turn your player so the blue axis is facing the same direction as the blue axis on the camera. then drag and drop the camera onto the player. now when you move the player, the camera will follow, and stay behind the player

AI scripting in Unity. Blocking Y rotation in code

I am creating a game where the world is 3D yet the characters are 2D. This means that my Y rotation must not change or else the 2D sprite rotates. I have a been scripting an AI and while the enemy does attract towards my player, he also rotates by 90 degrees. How can I modify my code to make it so that the sprite follows my player in the X and Z axis but the Y axis rotation stays zero.
//CODE STARTS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AISimple : MonoBehaviour
{
public Transform player;
float distancefrom_player;
public float look_range = 20.0f;
public float agro_range = 10.0f;
public float move_speed = 5.0f;
public float damping = 6.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
distancefrom_player = Vector3.Distance(player.position, transform.position);
if (distancefrom_player < look_range)
{
lookAt();
}
if (distancefrom_player < agro_range)
{
attack();
}
}
void lookAt()
{
Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
void attack()
{
transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
}
}
rigidbody has this functionality, if you tick freeze y rotation you'll be fine
okay, then try to modify y rotation before you set it
void lookAt()
{
Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
var euler = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping).eulerAngles;
euler.y = 0f;
transform.rotation = Quaternion.Euler(euler);
}