- Home /
Main Camera child under player, causes flip
I am building a 2d platformer, and I have my movement script complete; however I wanted the main camera to follow my character throughout the level, so I thought the best way to do this would be to place the camera as a child object under my player in the hierarchy. That way the camera moves alongside the player. This works alright except for in my player Movement script I use "transform.eulerAngles = new Vector2(0,180);" in order to flip the character when walking the other direction. When the camera is a child of the sprite, it flips the camera as well. Is there a way to do this without causing the camera to flip?
On a side note would it also be possible to make the camera follow the player, but only in the x or y planes?
Thanks for any help you can provide
Answer by 14ercooper · Aug 06, 2015 at 11:47 PM
This script will cause the camera to follow the player without rotating to the back when the player turns around. You might need to change with axis has the subtract 10 to make it display correctly. The subtraction amount (the 10 in the code) can be changed to adjust how close to the player the camera is, just make sure it is a positive integer.
using UnityEngine;
using System.Collections;
public class CameraUpdater : MonoBehaviour {
private Transform player;
void Start () {
player = GameObject.Find ("Player").transform;
}
void Update () {
transform.position = new Vector3 (player.position.x, player.position.y, player.position.z - 10);
}
}
Edit: Forgot how to use it. Un-parent the main camera from the player and add this as a script.
Answer by zeeshandar · Sep 18, 2014 at 04:11 PM
I saw this code somewhere hope it helps.
public Gameobject target;
private float trackSpeed = 10;
// Track target
void LateUpdate() {
float x = IncrementTowards(transform.position.x, target.transform.position.x, trackSpeed);
float y = IncrementTowards(transform.position.y, target.transform.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
}
}
Just drag and drop the player object in the script..
Answer by Slev · Sep 18, 2014 at 03:30 PM
I assume the rotation is to handle the sprite direction? Rather than adjust the character's euler angles, simply flip the sprite's X component, that will render it in reverse. For movement it's likely safer to use absolute left/right, rather than relative right.