U53R
U53R

Reputation: 1

using mathf.clamp as boundary for different size of screen

i currently have a gameobject named "block" with two long cubes next to each other with a gap between them. now when a user touches the screen and drags left or right the block also moves in that direction. now i am trying to setup a boundary so they can go up to a certain amount in the left or right direction. however how can i code this so it is the same for different screens eg iphone ipad etc.

the code i am currently using makes the block overlap each other getting rid of the gap which needs to be there. how do i go about to fix this. the code is below:

 public float speed = 0.0F;
 void Update() {
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
        // Get movement of the finger since last frame
        Vector3 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

        // Move object across XY plane
        transform.Translate(touchDeltaPosition.x * speed, 0, 0);

        Vector3 boundaryVector = transform.position;   
        boundaryVector.x = Mathf.Clamp (boundaryVector.x, -1f, 1f);
        transform.position = boundaryVector;
    }
}

blocks in unity

Upvotes: 0

Views: 913

Answers (1)

utkdub
utkdub

Reputation: 274

For screen size problem I recommend u put some Image Ui at the background and then according to different resolution set it Using anchor property and .

Make height to width ratio 0.5,Set UI scale to screen size...all these in Inspector Only. Get the left and right boundary values from Transform and then in block gameobj script use it as follows :

//windows specific code

            float x=Input.GetAxis ("Horizontal");
            if (x == 0) {
                Stop ();
            } else if (x > 0) {
                MoveRight ();
            } else if (x < 0) {
                MoveLeft ();
            }
            pos = transform.position;      //left                   //right
            pos.x=Mathf.Clamp (pos.x, "your boundry min to", "Your boundry max");
            transform.position = pos;

for overlap problem u can make use of Parent/ child property in Block .Make one the child of another..in this way If u move left the right block will also move left and they will not overlap....

Upvotes: 1

Related Questions