gpt4 book ai didi

Swift Sprite Kit 开启触控功能

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:00 24 4
gpt4 key购买 nike

我在搞一个 xcode 项目,我试图让一个红球 SKShapeNode 在我触摸它时四处移动。我自己在触摸开始类中的源代码没有做到这一点。我的代码有什么缺陷,我需要做什么才能修复它。

import SpriteKit

class GameScene: SKScene {

//Rectangle Skeletions
var leftWallRect = CGRect(x: 0, y: 0, width: 40, height: 1000)

var ball = SKShapeNode(circleOfRadius: 25);


override func didMoveToView(view: SKView) {

// Declare the Sprites in your scene
var ball = SKShapeNode(circleOfRadius: 25);
let leftWall = SKShapeNode(rect: leftWallRect);
let rightWall = SKShapeNode(rect: leftWallRect);
let pin = SKSpriteNode(imageNamed: "pin");

// Ball Properties
ball.strokeColor = UIColor.blackColor()
ball.fillColor = UIColor.redColor()
ball.position = CGPointMake(self.frame.width / 2 , self.frame.height / 4 - 100 )
self.addChild(ball)

// Left Wall Properties
leftWall.fillColor = UIColor.purpleColor()
leftWall.strokeColor = UIColor.blackColor()
leftWall.position = CGPointMake(self.frame.size.width / 3 - 45, self.frame.size.height / 2 - 400)
self.addChild(leftWall)

//Right Wall Properties
rightWall.fillColor = UIColor.purpleColor()
rightWall.strokeColor = UIColor.blackColor()
rightWall.position = CGPointMake(self.frame.size.width / 2 + 175, self.frame.size.height / 2 - 400)
self.addChild(rightWall)
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */

let touch = touches.first as! UITouch
let touchLocation = touch.locationInNode(self)

if touchLocation == ball.position{

ball.position = touchLocation

println("Touches");
}
}

override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}

最佳答案

LOL 哇,这很有趣,if touchLocation == ball.position 如果您能击中球的确切像素位置,我会印象深刻。你想要的是这个:

let touch = touches.first as! UITouch
let touchLocation = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(touchLocation)
if touchedNode == ball{
...

但就个人而言,我会做的是创建一个 SKSpriteNode 的子类,并在这个 child 的触摸例程中编写你的球的触摸代码

关于Swift Sprite Kit 开启触控功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34459988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com