My Camera Follow script is not very smooth. How can I smoothen the movement of the camera?
Here it is:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
void Start () {
targetPos = transform.position;
}
void FixedUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
}
The script makes the camera follow a rotating target.
You are updatng camera position on FixedUpdate. Change it to LateUpdate. FixedUpdate is designed for other purposes and is called less often usually then every frame. LateUpdate is called every frame and after Update so if your target is updated on Update camera will update its position later, what is desired.
Related
public GameObject player;
public Rigidbody rb;
private Vector3 offset;
public Vector3 minCamAngle;
public Vector3 maxCamAngle;
void Start()
{
rb = player.GetComponent<Rigidbody>();
offset = transform.position - player.transform.position;
}
// Update is called once per frame
void LateUpdate()
{
Quaternion desiredRotation = Quaternion.LookRotation(new Vector3(Mathf.Clamp(rb.velocity.x, minCamAngle.x, maxCamAngle.x), Mathf.Clamp(rb.velocity.y, minCamAngle.y, maxCamAngle.y), Mathf.Clamp(rb.velocity.z, minCamAngle.z, maxCamAngle.z)));
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime);
transform.position = player.transform.position + offset;
}
This is the code i'm using to rotate the camera based on the players velocity except when i set the minimum and maximum x rotation angle to 34 the camera always sets its rotation to an X rotation of -65.61 at the start of the game. I'm not sure what is happening and some help would be appreciated, Thanks.
If you dont collide with something you can fly! its really strange, please help me if you can.
i dont know how to fix it cause i am new in it.
Here is a script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
public float speed = 4.0f;
public float gravity = -9.8f;
private CharacterController _charCont;
// Use this for initialization
void Start()
{
_charCont = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed); //Limits the max speed of the player
// movement.y = gravity;
movement *= Time.deltaTime; //Ensures the speed the player moves does not change based on frame rate
movement = transform.TransformDirection(movement);
_charCont.Move(movement);
}
}
I don't know that CharacterController but it sounds like it takes the global movement vector.
After
movement = transform.TransformDirection(movement);
you should erase the Y component
movement.y = 0;
So I have been stuck on player movement for 15 hours total. My player jitters while it moves. I notice that the jitters aren't bad if:
A) I put CamPos code in the same lateUpdate() Function as PlayerMovement code
B) If I lower the fixed timestep under Time in project settings (makes jitter less notable)
I want to make it so that my player doesn't jitter using the right methods. My player has isKinematic off because it causes him to go through walls. I move using rigidbody movePosition because I don't know how to use rb.velocity to make the player move in the same direction as the camera.
I am using a camera for the third person and using rigidbody for movement.
Here's my current code on the player PlayerMovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public Rigidbody rb;
public Transform camPos;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
camPos = Camera.main.transform;
}
private void FixedUpdate()
{
if (Input.GetKey("w"))
rb.MovePosition(transform.position + (camPos.forward * speed));
if (Input.GetKey("s"))
rb.MovePosition(transform.position + (-camPos.forward * speed));
if (Input.GetKey("d"))
rb.MovePosition(transform.position + (camPos.right * speed));
if (Input.GetKey("a"))
rb.MovePosition(transform.position + (-camPos.right * speed));
}
}
Here's my current code on the camera CamPos:
//Hakeem Thomas
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamPos : MonoBehaviour
{
public Transform target;
public float smoothTime = 0.5F;
private Vector3 velocity = Vector3.zero;
public GameObject player;
private float mouseX, mouseY;
public int mouseX_Speed, mouseY_Speed;
//mouseSensitivity
public int turnSpeed;
void getMouseXY()
{
mouseX += Input.GetAxis("Mouse X") * smoothTime;
mouseY -= Input.GetAxis("Mouse Y") * smoothTime;
}
void LateUpdate()
{
getMouseXY();
// Define a target position above and behind the target transform
Vector3 targetPosition = target.TransformPoint(new Vector3(0, 1.5f, -2.5f));
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
transform.LookAt(target);
target.rotation = Quaternion.Euler((mouseY * mouseY_Speed), (mouseX * mouseX_Speed), 0);
player.transform.rotation = Quaternion.Euler(0, (mouseX * turnSpeed), 0);
}
}
I also tried using Vector3's and input Axis to move, but it makes the player move in an awkward way(Controls tied to one direction). I also tried using cinemachine and turned off all my scripts on my camera to make sure the camera wasn't jittering.
Rigidbody is the physic representation of your gameobject. The thing is you doesn't use the velocity / movement of the gameobject using dirrectly the rb.MovePosition().
But it is fine ! according to the documentation you have to enable the rigidbody "interpolation" to create a smooth transition between frames.
Hope i helped you and it will works for you !
Edit
dont forget to multiply your vector by Time.fixedDeltaTime inside FixedUpdate()
I need to rotate the camera around my player gameobject while holding the left mouse button. How would I approach this?
Also, I've read a bit on Vector 3, but I don't have a full understanding of it. Anybody who could explain it would be greatly appreciated.
I've looked at youtube videos and this one is exactly the concept I was looking for. I was just having trouble applying it to my code.
I'm on a bit of a time crunch, exams are nearing and my teacher hasn't explained most things that are explained in the video.
// This is my code inside the camera which follows the ball/player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptBallCam : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
void Start()
{
offset = transform.position - player.transform.position;
}
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
//End of code inside camera
//Code inside of player/ball
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptBall : MonoBehaviour
{
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
// end code
Results I'm expecting are exactly shown at 1:22 in
https://www.youtube.com/watch?v=xcn7hz7J7sI
Try this. The script goes on your camera.
Basically this script works by first getting the direction your mouse has moved in. In this case the X axis Mouse X (left/right direction). Then we take our rotation speed turnSpeed, and use it to rotate around the player by that amount of degrees using Quaternion.AngleAxis. Finally we make sure that the camera is always looking at the player by using transform.LookAt
using UnityEngine;
using System.Collections;
public class OrbitPlayer : MonoBehaviour {
public float turnSpeed = 5.0f;
public GameObject player;
private Transform playerTransform;
private Vector3 offset;
private float yOffset = 10.0f;
private float zOffset = 10.0f;
void Start () {
playerTransform = player.transform;
offset = new Vector3(playerTransform.position.x, playerTransform.position.y + yOffset, playerTransform.position.z + zOffset);
}
void FixedUpdate()
{
offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
transform.position = playerTransform.position + offset;
transform.LookAt(playerTransform.position);
}
}
There is a lot of information on this topic over here:
https://answers.unity.com/questions/600577/camera-rotation-around-player-while-following.html
I have an object called Ball, and I added keyboard interactivity to it(WASD to move the ball)
I need the camera to stay behind and follow the ball, but I am getting errors.
using UnityEngine;
using System.Collections;
public class ballmain : MonoBehaviour {
public bool isMoving = false;
public string direction;
public float camX;
public float camY;
public float camZ;
// Use this for initialization
void Start () {
Debug.Log("Can this run!!!");
}
// Update is called once per frame
void Update () {
camX = rigidbody.transform.position.x -=10;
camY = rigidbody.transform.position.y -=10;
camZ = rigidbody.transform.position.z;
camera.transform.position = new Vector3(camX, camY, camZ);
//followed by code that makes ball move
}
}
I get error "Assets/ballmain.cs(18,44): error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable"
Does anyone know the answer? If I comment out the code about the camera the ball can move around.
here you go . a full code.
Simple Following
using UnityEngine;
using System.Collections;
public class Follow: MonoBehaviour {
public Transform target;
public float smooth= 5.0f;
void Update (){
transform.position = Vector3.Lerp (
transform.position, target.position,
Time.deltaTime * smooth);
}
}
Advanced Following
using UnityEngine;
using System.Collections;
public class SmoothFollowScript: MonoBehaviour {
// The target we are following
public Transform target;
// The distance in the x-z plane to the target
public int distance = 10.0;
// the height we want the camera to be above the target
public int height = 10.0;
// How much we
public heightDamping = 2.0;
public rotationDamping = 0.6;
void LateUpdate (){
// Early out if we don't have a target
if (TargetScript.russ == true){
if (!target)
return;
// Calculate the current rotation angles
wantedRotationAngle = target.eulerAngles.y;
wantedHeight = target.position.y + height;
currentRotationAngle = transform.eulerAngles.y;
currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position.y = currentHeight;
// Always look at the target
transform.LookAt (target);
}
}
}
If you just simply want to follow the target object align the position of the camera the way you want it and make the camera the child of the target object and the rest will do
Here're one script I found useful during my game development. I didn't create them so I give credit to wiki.unity3d.com for providing this amazing script.
Smooth Follow:
using UnityEngine;
using System.Collections;
public class SmoothFollow2 : MonoBehaviour {
public Transform target;
public float distance = 3.0f;
public float height = 3.0f;
public float damping = 5.0f;
public bool smoothRotation = true;
public bool followBehind = true;
public float rotationDamping = 10.0f;
void Update () {
Vector3 wantedPosition;
if(followBehind)
wantedPosition = target.TransformPoint(0, height, -distance);
else
wantedPosition = target.TransformPoint(0, height, distance);
transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);
if (smoothRotation) {
Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else transform.LookAt (target, target.up);
}
}
More information about my work
Include Standard Mobile Asset to your project. It contains a SmoothFollow2D.js code in its script section. Attach this code with the gameobject and initialize public variables. This will simply do the job for you.
I found this simple and useful unity 2d camera follow script.
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
// Use this for initialization
void Start () {
targetPos = transform.position;
}
// Update is called once per frame
void FixedUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
}
source unity2d camera follow script
The -= in these lines:
camX = rigidbody.transform.position.x -=10;
camY = rigidbody.transform.position.y -=10;
is wrong. The -= will attempt to modify the rigidbody.transform.position. You just want -.
However, as it stands, the camera won't track changes in the target's Z position, nor will it track properly if the camera is rotated. To get the correct position you need (in vectors):-
cam_pos = target_pos - dist_to_target * cam_look_at