I’m trying to create a Legend of Zelda NES like game where when the player walks out of frame they hit a trigger and the camera is teleported to the room the player is in.
I’m going to make a few assumptions feel free to correct me if I’m wrong:
-
in the current room the camera is either stationary above the player or following him.
-
by “teleport” you don’t mean an instant movement into the new room, but a camera span towards the new room e.g.
https://www.youtube.com/watch?v=6ADhznw1zhc -
you’re not changing scenes
TRIGGERING THE EVENT
To trigger an event with a player you need a two things:
- a player with a collider AND a rigidbody
- a collider with a trigger
to make the collider with a trigger make a 2d sprite and set it to where you want this event to happen, then create a 2d collider and delete the sprite renderer part. You can do this without making the sprite but the sprite is easier to see.
Set the tag of the gameobject to something unique:
Then in a player script you should be able to type OnTriggerEnter2d (this option should appear as you type, this is a unity specific function name, not a custom one I made up. Here’s a snippet from my current game:
If you’re having trouble getting the collider script part to work properly there are lots of threads + tutorials out there lots of people struggle with this at first.
MOVING THE CAMERA
the camera in your game will have a vector 3 position and to move it all you need to do is change it’s transform.position in a unity script. i.e. in c# transform.position = new Vector3(5f,10f,-10f);
if you want to call your camera in a different script you can use Camera.main.transform.position or declare a Transform variable and assign the camera gameobject to it.
To move the camera instantaneously all you need is the new position you want your camera to be at. then set it’s position in a unityscript (in the example above you might want your camera to be at 5,10,-10.
If you want to move the camera over a set amount of time you’ll need to do a bit more
you’ll need to set some variables:
- new position for the camera (Vector3)
- old position for the camera (Vector3)
- time to move the camera between positions (float)
- the time that has passed since triggering this event (float)
Then all you need to do is use the Lerp function in the script’s update area.
Basically Lerp will set a number (or a vector3 in this case) to a precise position on a straight line between the start and end point.
so in the update section you would write something like:
This isn’t perfect and will require some additional thinking on your end to get it right but I think it’s a good start towards what you want.