- Home /
2d camera script, strange glitches appears
Hi guys I have written a camera script which is working pretty much the way I want it to. However, glitches that seems strange to me appears when my character moves. What the script does i basically to move the camera between two positions, depending on which direction the player is moving in but also leaving a distance for the player to move in without camera movement. The errors that happens is that sometimes the script doesn't respond immediatly so that the camera stays in the "wrong" position for a while before it finds the right spot again. I'm guessing the error is caused by some less than optimal solution I chosen. However, I've been trying hard to find out what it is but so far no luck. Any one with more experience who might see what could cause the glitches?
using UnityEngine;
using System.Collections;
public class Kameraflytt : MonoBehaviour
{
GameObject Spelaren;
float vikelseposx = 1.5f;
float avstand = 1.5f;
float minX = 1.3f;
float maxX = 13.6f;
float targetposx;
float kam_avstand;
bool pos1 = true;
bool pos2 = false;
void Start ()
{
Spelaren = GameObject.Find ("Spelaren");
}
void LateUpdate ()
{
kam_avstand = transform.position.x-Spelaren.transform.position.x;
if (kam_avstand < -(vikelseposx + avstand) && pos2)
StartCoroutine ("TillPos1");
if(Input.GetAxis ("Horizontal")>0 && pos1 && transform.position.x == Spelaren.transform.position.x + avstand)
transform.position = new Vector3 (Mathf.Clamp (Spelaren.transform.position.x + avstand,minX,maxX), 4f, -1f);
if(kam_avstand > avstand + vikelseposx && pos1)
StartCoroutine ("TillPos2");
if(Input.GetAxis ("Horizontal")<0 && pos2 && transform.position.x == Spelaren.transform.position.x - avstand)
transform.position = new Vector3 (Mathf.Clamp (Spelaren.transform.position.x - avstand,minX,maxX), 4f, -1f);
}
IEnumerator TillPos1 () {
float time = 3f;
float i = 0.0f;
float rate = 1.0f / time;
while (i < 1.0) {
i += Time.deltaTime * rate;
targetposx = Mathf.Lerp (transform.position.x, Spelaren.transform.position.x + avstand, i);
transform.position = new Vector3 (Mathf.Clamp (targetposx,minX,maxX), 4f, -1f);
yield return null;
}
pos2 = false;
pos1 = true;
}
IEnumerator TillPos2 () {
float time = 3f;
float i = 0.0f;
float rate = 1.0f / time;
while (i < 1.0) {
i += Time.deltaTime * rate;
targetposx = Mathf.Lerp (transform.position.x, Spelaren.transform.position.x - avstand, i);
transform.position = new Vector3 (Mathf.Clamp (targetposx,minX,maxX), 4f, -1f);
yield return null;
}
pos1 = false;
pos2 = true;
}
}