koryakinp
koryakinp

Reputation: 4125

Unity3d top-down camera control

I have a top-down game in Unity3D where a player can control a car. For now a camera keeps the car in the middle of the screen and rotates to the direction the car is pointing to.

That is how I did it:

public class CameraFollowController : MonoBehaviour
{
    private void FixedUpdate()
    {
        transform.rotation = Quaternion.Euler(90, car.rotation.eulerAngles.y + 90, 90);
        transform.position = new Vector3(car.position.x, cameraHeight, car.position.z);
    }

    public Transform car;
    public float cameraHeight = 10;
}

I want to shift the camera position, so the car is always on the bottom of the screen:

enter image description here

How to do that ?

Upvotes: 0

Views: 341

Answers (2)

Savaria
Savaria

Reputation: 565

If the car is moving on the x/y axis you can use transform.forward to get the direction the car is facing, then adjust it.

public float distance; // How much you want to offset

// Get the direction of the car
Vector3 dir = car.transform.forward;

// Offset the position
transform.position += -dir * distance;

Upvotes: 2

Eissa
Eissa

Reputation: 700

It looks like you're trying to offset the position of the camera on the Z-axis.

What you need to do is find out what the position offset is for the car to exist at the bottom of the screen and apply it as the Z-axis offset in your FixedUpdate() loop.

transform.position = new Vector3(car.position.x, cameraHeight, car.position.z *-/+* zCamOffset);

A fairly simple and rough way to figure out that offset is to, in play mode, move the car GameObject so that it sits at the location along the bottom of the game window. Then use the value in the Z-axis of the transform component for the car GameObject as the rough offset.

Best of luck!

Upvotes: 0

Related Questions