简体   繁体   中英

touch phases behavior issue

I'm making a 2D game in Unity3D for touch screen devices, and I'm trying to make something like "GetMouseButtonDown". Here is my code:

if (Input.touchCount > 0) {

    foreach (Touch touch in Input.touches) {
        Vector3 i = Camera.main.ScreenToWorldPoint (touch.position);
        RaycastHit2D hit = Physics2D.Raycast (i, i);
        if (hit.transform != null) {

            string tag = hit.transform.gameObject.tag;

            if (touch.phase == TouchPhase.Began) {
                    hit.transform.localScale = new Vector2(-transform.localScale.x, -transform.localScale.y);
            }

        }
    }
}

I want the hited object to change scale. And I want it to be as it would be if I use "GetMouseButtonDown". However, as a result, I press on it, and its scale changes, but only once. I press again, and nothing happens. What should I do?

The problem is not related to the touch phases behaviour, you're implementing it well.

The problem is that you are setting your gameobject to the same scale each time you're touching it. To well your gameobject you must set the hit.transform.localScale like this:

hit.transform.localScale = new Vector2(-hit.transform.localScale.x, -hit.transform.localScale.y)

Note that you were setting x and y scale to transform.localScale ,which is a constant value, each time you touch the gameobject.

Also note that with this sentence you're just fliping the scale each time you touch the gameobject. If you want to scale iteratively your gameobject so that it becomes smaller you have to do something like this:

float scaleFactor = -0.2f;
hit.transform.localScale += new Vector2(hit.transform.localScale.x*scaleFactor, hit.transform.localScale.y*scaleFactor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM