Hey guys,
I’m new to coding and I’m having an issue with trying to work out a way to code an endless runner death scene where if the character is not running fast enough or the character comes to a stop, the camera will catch up and the character will eventually die.
Can anyone please provide some suggestions on how i can go about this?
Thanks!
I’m guessing you don’t want the camera to lag behind the player too far, so you’ll need either a maximum distance, prevent the player from running too far, or a nonlinear speed with a minimum speed.
Assuming you’re using an orthographic camera in a 2D game, you can just check the players transform.position and kill it if the horizontal component is less than the camera’s transform.position (minus half the width of the cameras viewing volume). It would look something like this:
Camera cam;
float camWidth;
void Start()
{
cam = Camera.main;
camWidth = cam.orthographicSize * cam.aspect;
}
void Update()
{
if(player.transform.position.x <= cam.transform.position.x - camWidth)
{
//kill player
}
}
That assumes the player is running to the right, and they die when they hit the left side of the screen. You might need to add a small offset value so the left side of the player lines up with the screen.
2 Likes
Thanks Scabbage! I’ll give that a go!
Hey Scabbage,
I wrote the below script to move the main camera towards the player incrementally.
float step = speed * Time.deltaTime;
Vector3 temp = new Vector3(transform.position.x, transform.position.y, target.transform.position.z);
transform.position = Vector3.MoveTowards(transform.position, temp, step);
However i am unable to limit the max distance between the player and the camera.
Any suggestions on how to do this?
My camera is kinda odd in the game.
@jonathanlay Two ways, depending on the effect you want:
- Multiply the step variable by the distance between the target and current transform.
This will make the camera speed increase the farther away from the target.
- Clamp the position so it will still move at the same speed, but stops abruptly as it hits the wall.
The first is trivial, the second can be done something like this:
float step = speed * Time.deltaTime;
Vector3 temp = new Vector3(transform.position.x, transform.position.y, target.transform.position.z);
if(Math.Abs(target.transform.position.z - transform.position.z) <= maxDistance)
{
transform.position = Vector3.MoveTowards(transform.position, temp, step);
}else
{
// might have to make max distance negative here, I don't know how your camera is set up relative to the spatial axes
transform.position = target.transform.position - new Vector3(0f, 0f, maxDistance);
}