I am trying to figure out how to make my camera follow a cloned prefab, but to no avail.
Is there something I should add to the code to help it find cloned objects?
using UnityEngine;
using System.Collections;
using ORKFramework;
public class CameraFollow : MonoBehaviour {
public Transform target;
public float m_speed = 0.1f;
Camera mycam;
// Use this for initialization
void Start ()
{
mycam =GetComponent<Camera> ();
}
// Update is called once per frame
void Update () {
mycam.orthographicSize = (Screen.height / 2f) / 1f;
if (target) {
transform.position = Vector3.Lerp (transform.position, target.position, m_speed) + new Vector3 (0, 0, -10);
}
}
}
I use the code below to track target and then when I use the camera in my other script I use mycam.SetTarget (currentPlayer.transform);
// Track target
void LateUpdate() {
if (target) {
float x = IncrementTowards(transform.position.x, target.position.x, trackSpeed);
float y = IncrementTowards(transform.position.y, target.position.y, trackSpeed);
transform.position = new Vector3(x,y, transform.position.z);
}
}
// Increase n towards target by speed
private float IncrementTowards(float n, float target, float a) {
if (n == target) {
return n;
}
else {
float dir = Mathf.Sign(target - n); // must n be increased or decreased to get closer to target
n += a * Time.deltaTime * dir;
return (dir == Mathf.Sign(target-n))? n: target; // if n has now passed target then return target, otherwise return n
}
}
Not sure how or when you instantiate the clone, but you need to store a reference to the clone and not to the prefab. So when the new clone is instantiated you should save it in a variable “GameObject prefabClone”. Then you can get the current position “prefabClone.transform.position” inside the Lerp method.
void LateUpdate()
{
GameObject Clone = GameObject.instantiate …;
MyCameraRefernce.SetTarget (Clone); // if there is a function called SetTarget pass you gameobject there .
or
MyCameraRefernce.Target = Clone; // if its a varrible .
You can save a reference when you instantiate objects:
//Define this:
GameObject newArrow;
public GameObject arrowPrefab;
void Update(){
if (Input.GetButtonDown("FireArrow"){
newArrow = (GameObject) Instantiate(arrowPrefab, //Pos, //Rotation);
//Now you can reference the arrow you just spawned. For example:
Camera.main.GetComponent<FollowScript>().Follow(newArrow);
}
}