- Home /
Stop character from moving out of camera sight
So I'm working on a mobile airplane shooter, and I want the character to stay on the screen, but if I put a box-collider at the edges, and switch to a different aspect ratio, the box colliders either stop the player too soon, or too late. Is there any way to stop my sprite from going of the scaling screen without boxcolliders?
Comment
Best Answer
Answer by bpaynom · Mar 02, 2019 at 09:55 PM
You can set those colliders by code at runtime. For example:
private void PutColliders()
{
GameObject left = new GameObject( "LeftCollider" , typeof(BoxCollider2D));
GameObject right = new GameObject( "RightCollider", typeof( BoxCollider2D ) );
GameObject top = new GameObject( "TopCollider", typeof( BoxCollider2D ) );
GameObject bottom = new GameObject( "BottomCollider", typeof( BoxCollider2D ) );
left.transform.SetParent( transform );
right.transform.SetParent( transform );
top.transform.SetParent( transform );
bottom.transform.SetParent( transform );
Vector2 leftBottomCorner = camera.ViewportToWorldPoint( Vector3.zero );
Vector2 rightTopCorner = camera.ViewportToWorldPoint( Vector3.one );
Debug.LogWarning( leftBottomCorner );
Debug.Log( rightTopCorner );
left.transform.position = new Vector2(
leftBottomCorner.x - 0.5f,
camera.transform.position.y
);
right.transform.position = new Vector2(
rightTopCorner.x + 0.5f,
camera.transform.position.y
);
top.transform.position = new Vector2(
camera.transform.position.x,
rightTopCorner.y + 0.5f
);
bottom.transform.position = new Vector2(
camera.transform.position.x,
leftBottomCorner.y - 0.5f
);
left.transform.localScale = new Vector3( 1, Mathf.Abs( rightTopCorner.y - leftBottomCorner.y ) );
right.transform.localScale = new Vector3( 1, Mathf.Abs( rightTopCorner.y - leftBottomCorner.y ) );
top.transform.localScale = new Vector3( Mathf.Abs( rightTopCorner.x - leftBottomCorner.x ), 1 );
bottom.transform.localScale = new Vector3( Mathf.Abs( rightTopCorner.x - leftBottomCorner.x ), 1 );
}
Your answer
Follow this Question
Related Questions
2d game sidescroller camera UNITY 5 1 Answer
Restrict 2D camera with a Quad? 0 Answers
Why does my app function correctly in Unity Remote but not compiled as an app? 0 Answers
2D Camera and Buttons UI for Local Player 0 Answers
Help check click out of UI 2 Answers