- Home /
Question by
jtiai · Aug 26, 2018 at 08:08 AM ·
character movementlimitcamera viewport
Limit object movement within camera view
I'm trying to limit object movement (character) so it can't go outside camera boundary. This is my code. Object stops moving at correct place but I can't "return" character back into allowed bounds. bottomPoint is always different from my object transform.position when movement stops. What I am doing wrong?
Vector3 vp = camera.WorldToViewportPoint(transform.position);
Vector3 bottomPoint = camera.ViewportToWorldPoint(new Vector3(0f, 0f, 1f));
// Does character go out of view?
if (vp.y < 0f) {
rb.velocity = Vector3.zero; // Stop movement
transform.position = new Vector3(transform.position.x, transform.position.y, bottomPoint.y);
return; // Short circuit other imput
}
Comment
Answer by jtiai · Aug 26, 2018 at 08:32 AM
Ah, found the problem my self. First, camera.ViewportToWorlPoint(...) should have vp.z as last parameter.
Secondly transform.position = new Vector3(...) last parameter should be bottomPoint.z of course.