我试图让“玩家” Sprite 缓慢地移动到屏幕上的触摸处。我现在的代码立即将 Sprite 移动到屏幕上发生触摸的位置。这是我当前的代码。谢谢!
//
// GameScene.swift
// testing
//
// Created by Matthew Jahnes on 7/3/18.
// Copyright © 2018 Matthew Jahnes. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var player = SKSpriteNode()
override func didMove(to view: SKView) {
self.anchorPoint = CGPoint(x:0.5, y:0.5)
player = SKSpriteNode(color: UIColor.red, size: CGSize(width: 90, height:90))
player.position = CGPoint(x:0, y:0)
self.addChild(player)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
player.position.x = location.x
player.position.y = location.y
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
最佳答案
你需要
- 创建一个将玩家移动到目的地点的 Action 。
- 停止之前的
move
操作(如果存在) - 运行新的
move
操作
这是代码
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let destination = touch.location(in: self)
let move = SKAction.move(to: destination, duration: 2)
player.removeAction(forKey: "move")
player.run(move, withKey: "move")
}
关于swift - 让 Sprite 缓慢移动到触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246822/