ios - 在 spritekit 游戏中获取屏幕的触摸位置
问题描述
我有一个精灵套件游戏,我想知道用户是否触摸了屏幕的左侧、右侧或中间(25/50/25)
在我触摸屏幕最左侧的那一刻,它说我在 x 轴上触摸 -450,而它应该是 0。我假设它获得了相对于场景的触摸位置,并且锚点开始 450 像素到右边,当我触摸 0 时给我 -450。
由于这是一个横向滚动条,因此移动 achor 不起作用,我需要屏幕的触摸位置:
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
var touchLeft : Bool = false
var touchRight : Bool = false
var touchMiddle : Bool = false
for touch in (touches) {
let location = touch.location(in: self)
if(location.x < self.size.width/4){
touchLeft = true
print("Left")
} else if(location.x > ((self.size.width/4) * 3)){
touchRight = true
print("Right")
} else {
touchMiddle = true
print("Middle")
}
}
}
解决方案
你几乎拥有它,只需考虑负数。
如果您不知道,SKScene 默认的中心是 0。这是因为默认锚点是 0.5,0.5。
由于您使用相机来处理滚动,因此您希望使用
touch.location(in: self.camera)
这样的方法,以便您始终相对于相机所在的位置而不是场景所在的位置进行触摸。
因此,只需将您的代码更改如下:
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
var touchLeft : Bool = false
var touchRight : Bool = false
var touchMiddle : Bool = false
for touch in (touches) {
let location = touch.location(in: self.camera)
if(location.x < -self.size.width/4){
touchLeft = true
print("Left")
} else if(location.x > ((self.size.width/4))){
touchRight = true
print("Right")
} else { //x is between -width / 4 and width / 4
touchMiddle = true
print("Middle")
}
}
}
推荐阅读
- c - 在 C 中,如何从 UNIX 中的二进制文件中删除数据(结构)?
- r - 计算R中数据框中组内的比例
- azure - 缺少“交换操作系统磁盘”选项
- angular - 如何使用 Angular 前端、Spring REST 后端和 CAS (web.xml) 获取 UserPrincipal?
- python - 如何在下一个正则表达式模式匹配之前获取整个字符串?
- c# - 在 WinForm C# 应用程序上播放 WebRTC 流
- r - 删除默认 ggplot 图例并创建自定义图例
- angular - PolarArea 图表的 Apexchart 最大 y 轴值
- java - 需要帮助来使用数组对象显示数组的所有数据(不能使用数组列表)
- java - 整数值同步