【问题标题】:Getting Sprite To Move Slowly Toward Touch让 Sprite 慢慢向触摸方向移动
【发布时间】:2018-07-09 13:31:13
【问题描述】:

我正在尝试让“玩家”精灵缓慢地向屏幕上的触摸点移动。我现在拥有的代码将精灵立即移动到屏幕上发生触摸的位置。这是我当前的代码。谢谢!

    //
//  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
}

}

【问题讨论】:

    标签: swift xcode sprite-kit


    【解决方案1】:

    你需要

    1. 创建将玩家移动到目标点的动作。
    2. 如果存在,则停止之前的 move 操作
    3. 运行新的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")
    }
    

    【讨论】:

    • 我会推荐一个可变的持续时间,否则你的角色会以不同的速度移动
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多