Unity touch input for Rolling Sky x axis control

╄→尐↘猪︶ㄣ 提交于 2019-12-24 02:03:50

问题


I have written some code that I would image would be a very simplistic version of something found in the player controller of a game like Rolling Sky.

void Update () {
    if (Input.GetMouseButton(0)) {
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
}

This code works well on desktop, but as expected, it doesn't perform so well on mobile (the platform of choice) Interestingly it just appears as if the player follows the finger similarly to simply using:

this.transform.position = new Vector3 (Input.mousePosition.x, this.transform.position.y, this.transform.position.z);

Can anyone help make the first code block work correctly on mobile?

Desktop behavior (Desired) https://www.youtube.com/watch?v=PjSzEresQI8

Mobile behavior (undesired) https://www.youtube.com/watch?v=OooJ_NJW7V0

Thanks in advance


回答1:


For some reason, Input.GetMouseButton is always true on Android (not sure about other platforms), so to force the repositioning to happen only when the user has "pressed down" on the screen I used this code:

if (Input.GetTouch(0).phase == TouchPhase.Moved){
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;



回答2:


I am assuming you want smoother movement of the ball, kinda like in the game, not instantly teleport it to where the player touches. To do so you could use a function called Lerp. Read more here

To achieve this you could replace this line of code

this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);

with this one

this.transform.position = Vector3.Lerp(this.transform.position, new Vector3 (this.transform.position.x , this.transform.position.y, this.transform.position.z),Time.deltaTime)

Hope that helps!



来源:https://stackoverflow.com/questions/43169474/unity-touch-input-for-rolling-sky-x-axis-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!