- Home /
2D Camera Script
Ok, so I am currently using the following script to manage my camera:
using UnityEngine;
using System.Collections;
public class GameCamera : MonoBehaviour {
private Transform target;
private float trackSpeed = 10;
// Set target
public void SetTarget(Transform t) {
target = t;
}
// 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
}
}
}
How can I make it so that the camera only tracks the player from left to right, and not up and down? Also, it is possible to modify the script so that the player appears at the bottom of the screen rather than the center?
Thanks.
Answer by robertbu · Dec 18, 2013 at 01:53 AM
If the code is only tracking left to right, then you can position the camera or character with any up/down relationship you want. It wouldn't be hard to change your script, but it is cleaner to use MoveTowards():
using UnityEngine;
using System.Collections;
public class GameCamera : MonoBehaviour {
private Transform target;
private float trackSpeed = 10;
// Set target
public void SetTarget(Transform t) {
target = t;
}
// Track target
void LateUpdate() {
if (target) {
var v = transform.position;
v.x = target.position.x;
transform.position = Vector3.MoveTowards (transform.position, v, trackSpeed * Time.deltaTime);
}
}
}
Answer by Tekksin · Dec 18, 2013 at 02:33 AM
Camera.main.transform.position = new Vector3(transform.position.x, 0, transform.position.z + 0);
where 0 is, input the appropriate values to fit your game world. The first 0 defines the position of the camera on the y axis, and the second zero controls the camera on the z axis, which would help if the camera is clipping out some of your scene at the default value.
Your answer
Follow this Question
Related Questions
how to create a 2d platformer camera with script 0 Answers
2.5D Platformer Camera 1 Answer
2D character controller getting stuck on walls 5 Answers
2d camera movement 1 Answer
Rotate Camera 1 Answer