rrbox / GameWidget

A simple UI layout tools for SpriteKit
MIT License
3 stars 0 forks source link

MouseMoved を取得できる UI #99

Open rrbox opened 1 year ago

rrbox commented 1 year ago
rrbox commented 1 year ago

SKNode のサンプルです。

class MouseTrackableNode: SKSpriteNode {
    var isContainMouse = false

    override func mouseEntered(with event: NSEvent) {
        self.color = .red
    }

    override func mouseExited(with event: NSEvent) {
        self.color = .white
    }

    func register(notificarionHandler: UINotificaitionHandler) {
        notificarionHandler.notificationCenter.addObserver(self, selector: #selector(self.receiveMouseMoved(notification:)), name: .mouseMoved, object: nil)
    }

    func getEvent(from notification: Notification) -> NSEvent {
        notification.userInfo!["event"] as! NSEvent
    }

    override func mouseMoved(with event: NSEvent) {
        let pos = event.location(in: self.parent!)
        if self.contains(pos) && !self.isContainMouse {
            self.mouseEntered(with: event)
            self.isContainMouse.toggle()
        } else if !self.contains(pos) && self.isContainMouse {
            self.mouseExited(with: event)
            self.isContainMouse.toggle()
        }
    }

    @objc func receiveMouseMoved(notification: Notification) {
        let event = self.getEvent(from: notification)
        self.mouseMoved(with: event)
    }
}
rrbox commented 1 year ago

SKScene と SKView の設定サンプルです。

class View: SKView {
    var sceneTrackingArea: NSTrackingArea?

    func setTrackingArea() {
        let scene = self.scene!
        let trackingArea = NSTrackingArea(
            rect: frame,
            options: [.mouseMoved, .activeAlways],
            owner: scene)
        self.addTrackingArea(trackingArea)
        self.sceneTrackingArea = trackingArea
    }

    override func updateTrackingAreas() {
        self.setTrackingArea()
    }

}
class Scene: SKScene {

    let notificationSystem = UINotificaitionHandler()

    override func mouseMoved(with event: NSEvent) {
        self.notificationSystem.mouseMoved(with: event)
    }
}