- Home /
The question is answered, right answer was accepted
Why are my 2D sprite GameObjects blinking and how do I fix this problem?
Hello. Firstly, I'd like to apologize because my code may be sloppy. I am a beginner. I wanted to have the camera follow the player game object which is a 2d sprite so I found a c# script online to work with. I only wanted the camera to follow the object along the Y-Axis and stay put along the X-Axis so I edited the script a bit. Before I made my changes, the 2d sprite game objects did not blink on play. After I made changes so that the camera did not move along the X-Axis, my 2d sprite game objects started to blink on play. Here is a video: https://youtu.be/0B9kkjXAPDs
Here is my code:
using UnityEngine;
using System.Collections;
public class SmoothCamera : MonoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform player;
Vector3 currentPos;
private float xCam;
void Start() {
xCam = GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0, 0)).x;
}
void FixedUpdate ()
{
Vector3 point = GetComponent<Camera>().WorldToViewportPoint(player.position);
Vector3 delta = player.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z));
Vector3 destination = transform.position + delta;
currentPos = new Vector3(xCam, transform.position.y, point.z);
transform.position = Vector3.SmoothDamp(currentPos, destination, ref velocity, dampTime);
}
}
I fixed it. I made some more changes to the code I found.
using UnityEngine;
using System.Collections;
public class SmoothCamera : $$anonymous$$onoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform player;
Vector3 currentPos;
Vector3 destination;
private float xCam, zCam;
void Start() {
xCam = GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0, 0)).x;
zCam = transform.position.z;
}
void FixedUpdate ()
{
destination = new Vector3(xCam, player.position.y, zCam);
currentPos = new Vector3(xCam, transform.position.y, zCam);
transform.position = Vector3.SmoothDamp(currentPos, destination, ref velocity, dampTime);
}
}
Follow this Question
Related Questions
Camera to follow a target within a circle? 1 Answer
Align rotation when using ScreenToWorldPoint 0 Answers
I want to put main camera floating 0 Answers
How to make the Health bar on Enemys head not be in relation to Player(main) Camera? 2 Answers
Gameobject to stay within the view of the camera - c# 3 Answers