- Home /
Question by
Abdola · Jan 22, 2015 at 10:27 PM ·
camera2dcamera follow
Camera follow not working (deadzone)!
Hi everyone. I'm having some trouble with my camera movement and i'd appreciate some help. The idea is the camera moves towards the player after they leave a deadzone in the middle of the area, but lets them move a bit inside the deadzone. Like Super Mario World. This is my code as is, but the deadzone doesn't seem to work. The camera doesn't move until the player reaches the middle of the screen where the deadzone is.
var Player: Transform;
var xDifference: float;
var yDifference: float;
var moveThreshold: float = 3;
var cameraSpeed: float = 3;
var abovePlayer: float;
function awake() {
//references the player (player tagged object)
Player = GameObject.FindWithTag("Player").transform;
};
function FixedUpdate() {
//keeps z co-ordinate the same
transform.position.z = -5;
//keeps camera above the player slightly
transform.position.y = Player.position.y + abovePlayer;
//calculates the difference between the player's x co-ordinates and the camera's
if(Player.transform.position.x > transform.position.x) {
xDifference = Player.transform.position.x - transform.position.x;
} else {
xDifference = transform.position.x - Player.transform.position.x;
};
//calculates the difference between the player's y co-ordinates and the camera's
if(Player.transform.position.y > transform.position.y) {
yDifference = Player.transform.position.y - transform.position.y;
} else {
yDifference = transform.position.x - Player.transform.position.y;
};
//checks whether the player is beyond the deadzone threshold and moves the camera acordingly
if (xDifference >= moveThreshold || yDifference >= moveThreshold) {
transform.position = Vector2.MoveTowards(transform.position, Player.transform.position,cameraSpeed*Time.deltaTime);
transform.position.z = -5;
transform.position.y = Player.position.y + abovePlayer;
//prevents the camera from going beyond the start of the level
if (transform.position.x < -2) {
transform.position.x = -2;
}
};
};
Help would be much appreciated!
Comment
how have you setup the deadzone, e.g. an object with collider? or could you do it this way ins$$anonymous$$d of via code?
The idea is the deadZone is calculated by the difference between the camera's coordinates and the player's
Your answer
![](https://koobas.hobune.stream/wayback/20220613181214im_/https://answers.unity.com/themes/thub/images/avi.jpg)