How to move camera on Unity 2D

I wanna make camera follow my character but nothing worked. Maybe I am doing smth wrong.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Camera: MonoBehaviour
{
    Transform player;
    
    private void Start()
    {
        player = GameObject.Find("Player").transform;
    }
    private void FixedUpdate()
    {
        playerVector = player.position;
        playerVector.z = 10;
        transform.position = Vector3.lerp(transform.position, playerVector, Time.deltaTime);
    }
}

Upvotes: 1

Views: 1574

Answers (2)

Swagrim
Swagrim

Reputation: 422

That's easier than you think of it! BTW please don't forget to mark my answer as helpful if it is (the tick) Get the code from here:

//viewArea is your player and change the off position to make the player in the center of the screen as per you want. Try changing its y axis up or down, and same with the x and z axis.
[SerializeField] private Transform viewArea;
[SerializeField] Vector3 off;
// This is how smoothly your camera follows the player
[SerializeField] [Range(0, 3)]
private float smoothness = 0.175f;
private Vector3 velocity = Vector3.zero;

private void LateUpdate() {
    Vector3 desiredPosition = viewArea.position + off;
    transform.position = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothness);
}

Hope it works!

Upvotes: 1

rustyBucketBay
rustyBucketBay

Reputation: 4561

Use the normal Update() not the FixedUpdate that is for physics.

Try:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Camera : MonoBehaviour
{
    Transform player;

    private void Start() {
        player = GameObject.Find("Player").transform;
    }
    private void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            transform.position = player.position - player.forward * 5;//behind the player
            transform.LookAt(player, Vector3.up); //look to player
        }
    }
}

Upvotes: 0

Related Questions