- Home /
2D Camera follow player up but not down
Hey everyone.
I'm using the code from the Unity 2D game example tutorial for my camera movement. Right now it follow the character in any direction.
What I want is that if my character moves up in the Y direction, the camera follows it, but if it moves down in the Y, the camera doesn't follow. Basically I want the bottom of the camera to be the kill trigger, so the player should never fall. I've tried several things to no success, any thoughts?
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public float xMargin = 0f;
public float yMargin = 0f;
public float xSmooth = 0f;
public float ySmooth = 0f;
public Vector2 maxXAndY;
public Vector2 minXAndY;
private Transform player;
void Awake ()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
bool CheckXMargin()
{
return Mathf.Abs (transform.position.x - player.position.x) > xMargin;
}
bool CheckYMargin()
{
return Mathf.Abs (transform.position.y - player.position.y) > yMargin;
}
void FixedUpdate ()
{
TrackPlayer();
}
void TrackPlayer ()
{
float targetX = transform.position.x;
float targetY = transform.position.y;
if(CheckXMargin())
targetX = Mathf.Lerp (transform.position.x, player.position.x, xSmooth * Time.deltaTime);
if(CheckYMargin())
targetY = Mathf.Lerp (transform.position.y, player.position.y, ySmooth * Time.deltaTime);
targetX = Mathf.Clamp (targetX, minXAndY.x, maxXAndY.x);
targetY = Mathf.Clamp (targetY, minXAndY.y, maxXAndY.y);
transform.position = new Vector3(targetX, targetY, transform.position.z);
}
}
Try removing the $$anonymous$$athf.Abs, it converts values to always be positive, so you won't have any returned negative values for going down or backwards.
have you found any reliable solution to this? i have gone all over the internet and this is the only place that covers this topic.
Answer by Hakumaru · Feb 26, 2014 at 08:00 AM
try something along the line of, there's a trigger that has its position equal to the camera -5 or so on the y, which brings the "killswitch" up, then when setting camera to the players position, you make it only equal on the y axis if a variable is True.
if(!movingDown){
targetY = Mathf.Clamp (targetY, minXAndY.y, maxXAndY.y);
}
That SHOULD work, i'm not positive since i cannot test it.
Your answer
Follow this Question
Related Questions
Cinemachine 2d camera problem 0 Answers
Camera script 1 Answer
Shaky player effect when I apply a damping camera follow script? 1 Answer
Smooth Camera 2D Follow Player 0 Answers
Camera dont move whit Smooth Follow 2D 0 Answers