提问人:user324885 提问时间:11/2/2023 更新时间:11/2/2023 访问量:35
Cljfx中的动画
Animation in Cljfx
问:
我想用Cljfx库编写简单的游戏。我需要我在画布上写的方块在关键事件发生后继续向四个方向之一移动。我决定制作一些动画:反复绘制和渲染画布。在这段时间里,Canvas 的状态一直在变化。绘制和渲染后,线程会在某个时间休眠。 但是在迭代过程中不会绘制任何内容。线程只是休眠到循环结束。只有在刷新画布之后。我可以用Cljfx做这么简单的动画吗?
在 project.clj 中
:dependencies [[org.clojure/clojure "1.10.0"]
[cljfx "1.7.22"]]
在 core.clj 中
(ns examp
(:require [cljfx.api :as fx])
(:import [javafx.scene.canvas Canvas]
[javafx.scene.paint Color]
[javafx.scene.input KeyCode KeyEvent]))
(def ^:const WIDTH 300) ;Canvas width
(def ^:const HEIGHT 300) ;Canvas height
(declare root)
(declare renderer)
;Our mutable state
(def state*
(atom
{:x (/ WIDTH 2)
:y (/ HEIGHT 2)}))
;Defining canvas
(defn canvas [{:keys [width height x y]}]
{:fx/type :canvas
:width width
:height height
:draw (fn [^Canvas canvas]
(doto (.getGraphicsContext2D canvas)
(.setFill Color/BLACK)
(.fillRect 0 0 width height)
(.setFill Color/GREEN)
(.fillRect x y 10 10)))})
;Function for handling events
(defn event-handle [event]
(if (= :event/scene-event (:event/type event))
(cond
(= KeyCode/RIGHT (.getCode ^KeyEvent (:fx/event event)))
(dotimes [_ 3]
(swap! state* update-in [:x] #(+ % 10))
(renderer {:fx/type root :state @state*})
(Thread/sleep 300))
(= KeyCode/LEFT (.getCode ^KeyEvent (:fx/event event)))
(dotimes [_ 3]
(swap! state* update-in [:x] #(- % 10))
(renderer {:fx/type root :state @state*})
(Thread/sleep 300))
(= KeyCode/DOWN (.getCode ^KeyEvent (:fx/event event)))
(dotimes [_ 3]
(swap! state* update-in [:y] #(+ % 10))
(renderer {:fx/type root :state @state*})
(Thread/sleep 150))
(= KeyCode/UP (.getCode ^KeyEvent (:fx/event event)))
(dotimes [_ 3]
(swap! state* update-in [:y] #(- % 10))
(renderer {:fx/type root :state @state*})
(Thread/sleep 150)))))
;Main window
(defn root [{:keys [state]}]
{:fx/type :stage
:showing true
:scene {:fx/type :scene
:on-key-pressed {:event/type :event/scene-event}
:root {:fx/type :v-box
:children [{:fx/type canvas
:width WIDTH
:height HEIGHT
:x (:x state)
:y (:y state)}]}}})
;Define randerer
(def renderer
(fx/create-renderer
:opts {:fx.opt/map-event-handler event-handle}))
;Render miain window
(renderer {:fx/type root :state @state*})
答: 暂无答案
评论