如何在Unity中将键盘控件转换为触摸屏

时间:2019-02-14 09:34:27

标签: unity3d touch 2d pong

在这里填写新手。使用Unity C#。我正在将PONG游戏从键盘控制移动到触摸屏。这是我的工作键盘代码:

// Player 1 =>用W / S键控制左蝙蝠

公共GameObject leftBat;

//使用它进行初始化 无效的开始(){

}

//每帧调用一次更新 void Update(){

//Defualt speed of the bat to zero on every frame
leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, 0f, 0f);

//If the player is pressing the W key...
if (Input.GetKey (KeyCode.W)) {

    //Set the velocity to go up 1
    leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, 8f, 0f);
}

//If the player is pressing the S key...
else if (Input.GetKey (KeyCode.S)) {

    //Set the velocity to go down 1 (up -1)
    leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, -8f, 0f);


}

}

我找到了这段代码并一直在使用它,但是现在仍然可用。

使用UnityEngine; 使用System.Collections;

公共类Player_Input_Controller:MonoBehaviour {

public GameObject leftBat;
public float paddleSpeed = 1f;
public float yU;
public float yD;

private Ray ray;
private RaycastHit rayCastHit;

private Vector3 playerPos = new Vector3(0, -9.5f, 0);

// Update is called once per frame
void Update () {

    if (Input.GetMouseButton (0))
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray, out rayCastHit)){
            Vector3 position = rayCastHit.point;

            float yPos = position.y;
            playerPos = new Vector3(Mathf.Clamp(yPos, yU, yD), -9.5f, 0f);
            transform.position = playerPos; 
        }
    }
}

}

任何人都有我可以使用的触摸屏Pong脚本,或者知道如何编辑该脚本?

再次,我真的很新,很抱歉,如果我看上去像班上的假人。

感谢您提供的任何帮助。对此,我真的非常感激。这是完成我的游戏的最后一个障碍。

1 个答案:

答案 0 :(得分:1)

我认为,您不需要进行任何射线广播。因为您使用的是2D模式,所以只关心Input.mousePosition的y值。因此,您可以使用相机的z值计算屏幕范围。如果您的相机位于(0, 0, -10),则可以说您在游戏中的范围在世界坐标中为-5 - BatOffset5+BatOffset。因此,您需要某种方法来将Screen.height映射到您从图像中可以看到的世界坐标范围。

enter image description here

最后,您需要找到Input.mousePosition.y将其除以Screen.height。这将为您提供触摸或单击位置的比率。然后找到在世界空间中的位置。

请注意:您也可以使用Input.touchPosition.y。以下脚本将为您执行此操作:

public GameObject cam;
private Vector3 batPos;
private float minY;
private float maxY;
private int Res;
private float deltaY;

void Start () {
    minY = cam.transform.position.z / 2 - gameObject.transform.localScale.y;
    maxY = (-cam.transform.position.z / 2) + gameObject.transform.localScale.y;
    deltaY = maxY - minY;
    Debug.Log(minY + " " + maxY + " " + deltaY);
    Res = Screen.height;

    batPos = gameObject.transform.position;

}

void Update () {
    if(Input.GetMouseButtonDown(0))
    {
        // we find the height we have to go up from minY
        batPos.y =minY + Input.mousePosition.y / Res * deltaY;
        gameObject.transform.position = batPos;
    }       
}

当您用鼠标单击屏幕时,这在编辑器中对我有用。您只需要将部分Input.GetMouseButtonDown更改为Touch之类的命令Touch.tapCount > 0。此脚本也应附加到蝙蝠上。祝你好运!

,您可以使用正交摄影机和正交摄影机尺寸来代替cam.transformation.z

相关问题