Sriram Kumar
Sriram Kumar

Reputation: 69

Unity 2D Android - Restrict object to within the screen

I am working on a 2D Game similar to Space Shooter. I developed it for Web and PC and it works great. I am now porting it to Android and am having an issue with the Player code.

The player(a space ship) will be at the bottom of the screen and it moves left to right within the screen. I wrote a piece of code which limits the player within the screen and here is the code:

private float screenx = Screen.width -20;
playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);

if(Input.GetKey(KeyCode.RightArrow) && playerPosScreen.x < screenx)
{
    transform.Translate(Vector3.right * speed * Time.deltaTime * 0.4f);
}

if (Input.GetKey(KeyCode.LeftArrow) && playerPosScreen.x > 20)
{
    transform.Translate(-Vector3.right * speed * Time.deltaTime * 0.4f);
}

I am aware that I still need to convert few of the static values in the above code and this is is not really a good way to code.

My question here is how do I do this in Android? I want the player to stay in the screen, i.e if the user moves the player by dragging him to extreme left, no matter how much ever he tries to drag, the player should stay at the left corner of the screen and the same applies to right. In simple terms I want to detect the left and right edges of the screen and limit my object within these edges.

My game will be in landscape mode.

Any help would be very much appreciated. Thanks in advance.

Upvotes: 3

Views: 6684

Answers (2)

Pramod
Pramod

Reputation: 196

public Transform player;
public float distanceFromCamera=10;
public float offsetx=.05f;
public float offsety=.05f;
void Awake()
{

    player.position=Camera.main.ViewportToWorldPoint(new Vector3(offsetx,offsety,distanceFromCamera));
}

this will be your bottom left screen boundry

Upvotes: 0

rhughes
rhughes

Reputation: 9583

This sort of problem is generally solved in the following manor:

if(transform.position.x < screenx) {

    transform.position.x = screenx;
}

Here, we are checking to see if the transformed player is out of the screen space. If it is, we set it to the minimum it can be - which I am assuming is screenx.

Upvotes: 2

Related Questions