简体   繁体   English

具有触摸位置Android的Unity 2D对象位置

[英]Unity 2D object position with touch position Android

i have a problem here, 我在这里有问题

i have an object called projectile and i want make that projectile appear where i touch my phone with screen resolution 1090x1820 , my logic is : 我有一个名为子弹的对象,我想让该子弹出现在触摸屏幕分辨率为1090x1820手机的1090x1820 ,我的逻辑是:

#pragma strict

var projectile:Transform;
private var shoot:Transform;

function Start () {

}


function Update () { 

     for (var i = 0; i < Input.touchCount; ++i) {
         var touch:Touch = Input.GetTouch(i);
         if (touch.phase == TouchPhase.Began) {
            shoot = Instantiate(projectile) as Transform;
            shoot.position.x = touch.position.x;
            shoot.position.y = touch.position.y;
         }
     }
 }

This code work well, except the projectile doesn't appear at screen. 该代码运行良好,但弹丸未出现在屏幕上。 Somehow, i try to put an object at unity editor and it's showing x = -2 and y = -1 or x =-1 and y =-5 and so on.I also try to Debug the touch position and it's showing x= 300 and y=90 etc. 不知何故,我尝试将一个对象放到unity编辑器中,它显示x = -2y = -1x =-1y =-5等,我还尝试调试触摸位置并显示x= 300y=90等。

How i can fix this ? 我该如何解决?

Sorry for my bad english ! 对不起,我的英语不好 !

Your problem is you are intermixing world coordinates with screen position. 您的问题是您正在将世界坐标与屏幕位置混合在一起。 To fix that you'll need to use ScreenToWorldPoint so your code would look similar to: 要解决此问题,您需要使用ScreenToWorldPoint,以便您的代码类似于:

    var worldPos : Vector3 = camera.ScreenToWorldPoint (touch.position));

    shoot.position.x = worldPos.x;

    shoot.position.y = worldPos.y;

This is untested code so use only for reference as it is there for you to understand the logic. 这是未经测试的代码,因此仅供参考,因为它可以帮助您理解逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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