unity3d: Camera does not follow the player - unity3d

I am fairly new in game development, I have a piece of code that makes camera move based on player's movement.
player's movement script:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
//to store movement
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLenghth = 100f;
//gets called regardless if the script is enabled or not
void Awake(){
floorMask = LayerMask.GetMask ("Floor");
playerRigidbody = GetComponent<Rigidbody> ();
//Input.ResetInputAxes ();
}
//unity calls automatically on every script and fire any physics object
void FixedUpdate(){
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
//Rotate ();
Turning ();
}
void Move(float h, float v){
movement.Set (h,0f,v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning (){
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (camRay,out floorHit,camRayLenghth,floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
}
and here is the script attached to the main camera:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
// a target for camera to follow
public Transform player;
// how fast the camera moves
public float smoothing = 4f;
//the initial offset from the target
Vector3 offset;
void start(){
//calculation of initial offset (distance) between player and camera
offset = transform.position - player.position;
Debug.Log ("offset is " + offset);
}
void FixedUpdate (){
//updates the position of the camera based on the player's position and offset
Vector3 playerCameraPosition = player.position + offset;
//make an smooth transfer of location of camera using lerp
transform.position = Vector3.Lerp(transform.position, playerCameraPosition, smoothing * Time.deltaTime);
}
}
but when I attach the script to my main camera, as soon as I play test the game camera starts to relocate and moves towards the ground even though the player hasn't moved yet. If I remove the script from the camera and make the camera the child of the player, as soon as I hit play, camera starts to rotate around the object.
Please give me some hints what am I doing wrong ?

The camera offset isn't being set because of the lower case on your start method. This means the offset remains at its default value which is 0,0,0 causing your camera to move to some funky place.
Change: `
void start() {
...
}
to
void Start() {
...
}

see you don't need any code for this just make you camera a child of your player object..
drag you camera object onto the player object in hierarchy

Related

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);
}
}

CHARACTER ROTATION depending on camera IN UNITY

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);

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)

Unity 2D Top-Down mouse facing weapon rotation problem

I am making a Top-Down 2D shooting game and i did spot a trouble.
The point is, player gun has weird rotation whenever the player rotate.
I made my Player face mouse position. Player gun is not in the center of sprite.
The Gun is a prefab in PlayerHand and PlayerHand is a Child of Player.
I tried a lot of things and yet still i cant find a solution.
public class HandHolder : MonoBehaviour
{
[SerializeField] Gun gun;
[SerializeField] float offsetX;
[SerializeField] float offsetY = 0.01f;
Gun playerGun;
void Awake ()
{
playerGun = Instantiate(gun,transform.localPosition,transform.localRotation) as Gun;
}
// Update is called once per frame
void Update ()
{
playerGun.transform.position = new Vector3(transform.position.x + offsetX,transform.position.y + offsetY);
playerGun.transform.rotation = transform.rotation;
playerGun.Shooting();
}
}
void Update()
{
if (!isLocalPlayer)
return;
Vector3 position = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * 20f;
transform.position += position;
FaceMouse();
}
public void FaceMouse()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
mousePosition.Normalize();
float rotation_z = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
Here are the screenshoots. My Player already has a gun in texture. but it is only texture. I want the Gun prefab to be exactly on the place of Player sprite gun, whenever i rotate.
add an empty to your player, name it gunTransform. tag it GunTransform make sure the forward axis(blue) is facing the players forward direction.
Class Level variable -
Transform guntransform;
in Awake():
guntransform=this.GameObject.FindObjectWithTag("GunTransform").getComponent<Transform>();
then instead of
playerGun = Instantiate(gun, transform.localPosition, transform.localRotation) as Gun;
call
playerGun = Instantiate(gun, guntransform.position, guntransform.rotation) as Gun;

I'm trying to rotate my character to face the mouse position, only works relative to Transform: (0,0,0)

Character rotation, only happens when mouse is rotated around world centre (0,0,0) -
The MoveToMouse() works perfectly, click on a point in the world, and the player moves, and camera follows.
But when holding shift to rotate the character to where mouse is pointing, it only points relative to the world centre.
transform.LookAt - works perfectly, but I want to be able to smooth the rotation.
using UnityEngine;
using UnityEngine.AI;
public class ClickToMove : MonoBehaviour
{
NavMeshAgent player;
public float rotSpeed = 10f;
void Start()
{
player = GetComponent<NavMeshAgent>();
}
void Update()
{
MoveToMouse();
LookAtMouse();
}
void MoveToMouse()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
player.destination = hit.point;
}
}
}
void LookAtMouse()
{
if (Input.GetKey(KeyCode.LeftShift))
{
RaycastHit lookHit;
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out lookHit, 100);
//transform.LookAt - works perfectly, but want to be able to smooth the rotation.
//transform.LookAt(lookHit.point);
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(lookHit.point), rotSpeed * Time.deltaTime);
}
}
}
Quaternion.LookRotation takes directional Vector as a parameter not a position.