How do i change the target for my camera?
I have a 2d sidescroller and the camera follows the player at the start but when I want the camera to follow the instantiated object it doesn't follow it. the target changes but the camera doesn't follow it.
void Update () {
if (Target) {
Vector3 posNoZ = transform.position;
posNoZ.z = Target.transform.position.z;
Vector3 targetDirection = (Target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 10f;
TargetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, TargetPos + offset, 0.50f);
} else {
Target = MountedGolem;
}
}
That is weird. Your code works fine for following the target game object so I'm guessing it must be something with assigning the target that is the problem.
Try this code, assign two objects in the editor for targetA and targetB, run it and see if the camera changes targets when you press spacebar.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CameraFollow : $$anonymous$$onoBehaviour
{
// Unity Editor Variables
[SerializeField] private Transform targetA;
[SerializeField] private Transform targetB;
// Private Variables
private Transform target;
// Use this for initialization
private void Start()
{
target = targetA;
}
// Update is called once per frame
private void Update()
{
if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.Space))
{
target = (target == targetA) ? targetB : targetA;
}
if (target)
{
Vector3 posNoZ = new Vector3(transform.position.x, transform.position.y, target.transform.position.z);
Vector3 targetDirection = (target.transform.position - posNoZ) * 10f;
Vector3 TargetPos = transform.position + (targetDirection * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, TargetPos, 0.50f);
}
}
}
Your answer
Follow this Question
Related Questions
Does anyone know the script for a smooth camera follow of the main game object? 8 Answers
How to choose a specific game object with a tag from multiple game objects with that tag? 0 Answers
Create a smooth camera without jittering/flickering in 2D 3 Answers
Help with setting up 2D auto scrolling camera using Cinemachine 1 Answer