- Home /
Question by
a1exi8 · Mar 12, 2013 at 03:17 AM ·
c#cameragameobjectposition
Getting camera to stick to object
hi all, I'm building a game which requires the camera to stick to my main object in the X axis. It's a bike based game, so the object will be riding off jumps, etc, but I don't want the camera to move up as the object does, only move along the X axis. Using C#, my code is as follows:
public Vector3 cameraFollowOffset = new Vector3(0,5,-5);
public Camera followCamera;
void Start(){
if (followCamera == null)
followCamera = Camera.mainCamera;
}
void Update(){
followCamera.transform.position = transform.position + cameraFollowOffset;
}
}
Many thanks
Comment
Answer by nsxdavid · Mar 12, 2013 at 09:19 PM
followCamera.transform.position = new Vector3(transform.position.x,0,0) + cameraFollowOffset;
Of course the Y and Z values (which I have as 0) in the above should be replaced with whatever makes sense for your scene.
Also, probably don't need the if (followCamera == null)
line... doesn't hurt, but doesn't really do anything useful either.