首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用球拍的“大刘海”感觉多键按压

如何用球拍的“大刘海”感觉多键按压
EN

Stack Overflow用户
提问于 2016-01-03 12:39:10
回答 1查看 983关注 0票数 2

我正在开发一个简单的小行星游戏在球拍和一切工作良好,但我想让球员在同一时间移动和射击。

以下是控制键:

  • 左/右旋转
  • 升[降]快,慢下来
  • 发射空间。

我的on-key处理程序:

代码语言:javascript
运行
复制
(define (direct-ship w a-key)
  (define a-ship (world-ship w))
  (define a-direction
    (+ (ship-direction a-ship)
    (cond
      [(key=? a-key "left") -5]
      [(key=? a-key "right") 5]
      [else 0])))
  (define a-speed
    (+ (ship-speed a-ship)
       (cond
         [(key=? a-key "up") 1]
         [(key=? a-key "down") -1]
         [else 0])))
  (define bullets
    (cond
      [(key=? a-key " ") (cons (new-bullet a-ship) (world-bullets w))]
      [else (world-bullets w)]))

  (world (world-asteroids w)
         (ship (ship-pos a-ship) a-direction a-speed)
         bullets
         (world-score w)))

考虑到这个过程的签名,它一次只能处理一个字符,这对我来说是有意义的。所以也许我需要用不同的处理程序?还是不同的钥匙?

参见github:https://github.com/ericclack/racket-examples/blob/master/asteroids4.rkt上的完整源代码

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-03 13:11:56

问题是,on-key处理程序一次只调用一个键。即使您能够同时按右箭头和向上箭头,on-key也将被调用两次。

处理此问题的一种方法是,每个键都要将信息存储在全局表中,以确定该键是向上还是向下。给定这样一个表,您可以在on-key中使用它来检查当前正在处理的键之外的键的状态。

以下是空间入侵者克隆人的片段。首先是全局键盘表。

代码语言:javascript
运行
复制
;;; Keyboard
; The keyboard state is kept in a hash table. 
; Use key-down? to find out, whether a key is pressed or not.
(define the-keyboard (make-hasheq))
(define (key-down! k) (hash-set! the-keyboard k #t))
(define (key-up! k)   (hash-set! the-keyboard k #f))
(define (key-down? k) (hash-ref  the-keyboard k #f))

然后是对事件的处理--这是由于上下文而没有big-bang完成的,但这里最重要的是它。

代码语言:javascript
运行
复制
;;; Canvas
; Key events sent to the canvas updates the information in the-keyboard.
; Paint events calls draw-world. To prevent flicker we suspend flushing
; while drawing commences.
(define game-canvas%
  (class canvas%
    (define/override (on-event e) ; mouse events
      'ignore)
    (define/override (on-char e)  ; key event
      (define key     (send e get-key-code))
      (define release (send e get-key-release-code))
      (when (eq? release 'press)  ; key down?
        (key-down! key))
      (when (eq? key 'release)    ; key up?
        (key-up! release)
        (when (eq? release #\space)
          (play-sound "shoot.mp3" #t))))
    (define/override (on-paint)   ; repaint (exposed or resized)
      (define dc (send this get-dc))
      (send this suspend-flush)
      (send dc clear)
      (draw-world the-world dc)
      (send this resume-flush))
    (super-new)))

如您所见,键事件处理程序只会存储键是否上下(出于某种奇怪的原因,可以播放"shoot.mp3“示例)。那么玩家实际上在哪里移动(根据箭头键)?

实际的移动是用on-tick (或其等效的)处理的。在on-tick中处理移动可以确保玩家在按下键时不会移动一个额外的距离。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34576612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档