- Home /
Why won't my camera follow my player?
So I'm new to Unity and I made this program, by following a guide and everithyng is the same in my program, but its just won't work. The thing is that I was the one who fixed the errors by myself, so I don't know if I messed up, or the program was wrong from the start.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowingCam : MonoBehaviour
{
private Transform playerTransform;
void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}
void LateUpdate()
{
Vector3 temp = playerTransform.position;
temp.x = playerTransform.position.x;
temp.y = playerTransform.position.y;
transform.position = temp;
}
}
What were the errors? Could you also link a video of the action. If all else fails, you can parent the camera to the player.
and you don't need these lines:
temp.x = playerTransform.position.x;
temp.y = playerTransform.position.y;
Yeah, he was probably thinking about not setting z to be the same and keep some distance in z, but then instead he ended up just setting all 3 axis to be just the same.
Answer by RodrigoAbreu · Feb 05, 2021 at 02:11 AM
@PbAbyss23 Well, what you're doing there is basically setting the camera position to be the same as the position of the player, instead of following it. We should consider two premisses here though, 1) this script is attached to a camera, 2) Your Player has the tag "Player" setup.
using UnityEngine;
public class FollowingCam : MonoBehaviour
{
private GameObject player;
private Vector3 offset;
void Start ()
{
player = GameObject.FindObjectWithTag("Player");
if (player != null)
{
offset = transform.position - player.transform.position;
}
else
{
Debug.LogError("Oops I forgot to add my player to the scene or to set the tag on it");
}
}
void LateUpdate ()
{
if (player != null)
{
transform.position = player.transform.position + offset;
}
}
}
Answer by Dragonlov46er · Feb 06, 2021 at 02:01 PM
I'm not sure but did you delete the SampleScene? I had this issue once and it was because I didn't delete the SampleScene.
Your answer
Follow this Question
Related Questions
How to change shape from cube to sphere and keep the code 1 Answer
How to make keywords per material works properly (not in Editor) 0 Answers
スクリプトが追加できません。,スクリプトクラスが見つからない (I can't add a script. , Script class not found) 0 Answers
Failed to re-package resources Facebook-unity-sdk-7.11.1 2 Answers
How i destroy the object of that part that collides with another object? 2 Answers