2D Camera RPG
Hi, i tried to make a camera for a 2D game (an rpg) can follow the player and collide with the end of the map. I tried jus drag and drop the camera inside the player, put some blocks at the edges of the map and putting a Box Collider on the camera. This works, but very glitchy, because when the camera collides with the block it seems like its bouncing and the player still walking to the edge (i wanted it) but when the player walks to the opposite side doesn't come back to the center of the camera. Any ideas? (Sorry, i got a really bad english)
Answer by ElijahShadbolt · Oct 27, 2016 at 04:01 AM
Instead of parenting the camera to the Player GameObject, you could add a script that constantly updates the position of the camera to be directly over the player, but within the bounds of a minimum and maximum world position, like so:
RPG2DCamera.cs
using UnityEngine;
public class RPG2DCamera : MonoBehaviour
{
public Transform target; // set to the Player GameObject
public Vector2 worldPosMin = new Vector2(-10f,-10f);
public Vector2 worldPosMax = new Vector2(10f, 10f);
void Update()
{
if (target != null)
{
Vector2 targetPos = target.transform.position;
float x = Mathf.Clamp(targetPos.x, worldPosMin.x, worldPosMax.x);
float y = Mathf.Clamp(targetPos.y, worldPosMin.y, worldPosMax.y);
transform.position = new Vector3(x, y, transform.position.z);
}
}
}
Just add this script to the Camera and remember to set the Player as its Target
in the inspector.
Thanks! It works really well. But i like UnityScript and i won't change it for anything, so if somebody needs the code in js:
#pragma strict
var target : Transform; // set to the Player GameObject
var worldPos$$anonymous$$in : Vector2 = new Vector2(-10f,-10f);
var worldPos$$anonymous$$ax : Vector2 = new Vector2(10f, 10f);
function Update () {
if (target != null) {
var targetPos : Vector2 = target.transform.position;
var x : float = $$anonymous$$athf.Clamp(targetPos.x, worldPos$$anonymous$$in.x, worldPos$$anonymous$$ax.x);
var y : float = $$anonymous$$athf.Clamp(targetPos.y, worldPos$$anonymous$$in.y, worldPos$$anonymous$$ax.y);
transform.position = new Vector3(x, y, transform.position.z);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612095515im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D box collider always detecting player,2D Box colliders detecting player when he is not there 1 Answer
2D movement with gravity shifting 0 Answers
CS1216 error 0 Answers
My explosion material is shown from the back of the screen but not from front 1 Answer
2D ROGUELIKE IN UNITY 5.x Level Error 0 Answers