- Home /
Trying to make the camera follow the player but stop at the edge.
As the title says I am trying to make the camera follow the player in a 2D platformer I am making, however it comes up with errors in this script, if any of you guys could help, I'm sorta new to Unity and c#. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollower : MonoBehaviour
{
private Transform myTransform;
public Transform PlayerTransform;
private void Awake ()
{
myTransform = GetComponent<Transform> ();
}
void LateUpdate ()
{
if (PlayerTransform.position.x <= .685449) {
myTransform.position.x = 0.685449;
}
else if (PlayerTransform.position.x >= 9.31455)
{
myTransform.position.x = 9.31455;
}
else
{
myTransform.position.x = PlayerTransform.position.x;
}
}
}
Answer by Divinegaming · Sep 04, 2017 at 07:54 PM
I think the problem is that transform.position
is a c# property . This means you cant modify x in that way. (think of property as functions without the ()
to call them)
The way you could update then position is to assign it to a variable first, then modify it, and finally set the position equal to the new position. Example:
var newPosition = transform.position;
// if statements here
newPosition.x = PlayerTransform.position.x;
transform.position = newPosition;
and of course add your if statements back in the middle as well.
Edit:
you can still do checks on properties, so if (PlayerTransform.position.x <= .685449)
will works.
Your answer
Follow this Question
Related Questions
Spikes for a platformer game 1 Answer
My 2D Player Can't Move (2d Photon Game) :(,My Player Don't Move (2d Character Controller 0 Answers
In my 2D platformer game, how would I create a height marker?, 1 Answer
Jumping from special jump orb 1 Answer
How to check if an object hits the ground hard enough then add explosive force around it (2D) 1 Answer