1. 程式人生 > >GODOT遊戲程式設計007---- Your First Game(2)

GODOT遊戲程式設計007---- Your First Game(2)

上一篇做了一個會移動的小人。
簡單回顧一下。我們要創設一個玩家角色,新建Area2D,這個包含兩個子節點,一是AnimatedSprite,也就角色的動畫圖片,二是 CollisionShape2D,也就是角色的範圍大小,用於判斷是否遭受到攻擊。我想,以後在設計得時候,是否可以用這個節點製作範圍傷害,如暴風雪?或者製作敵人的警戒圈?現在還不知道……
繼續後面的教程。
先來看寫的程式碼

extends Area2D    #拓展Area2D功能

export (int) var speed  # 輸出角色移動速度變數 (pixels/sec).
var screensize  # 變數遊戲視窗尺寸.
func _ready(): screensize = get_viewport_rect().size #_ready() 當一個節點進入場景時呼叫,是我們獲取螢幕尺寸的好時機。 func _process(delta): var velocity = Vector2() #定義角色移動速度的二維向量。 # 我們用_process()函式來定義角色動作。 #_process函式每幀都呼叫,所以我們用來更新一些經常改變的元素。 #現在,我們要用它實現: #一檢查輸入,二向給定方向移動,三角色有適當的動畫。 #首先我們來檢查四個預設的方向鍵有沒有按下
if Input.is_action_pressed("ui_right"): velocity.x += 1 if Input.is_action_pressed("ui_left"): velocity.x -= 1 if Input.is_action_pressed("ui_down"): velocity.y += 1 if Input.is_action_pressed("ui_up"): velocity.y -= 1 #上面可以看到,input這個函式的一個功能用法
if velocity.length() > 0: velocity = velocity.normalized() * speed #速度 $AnimatedSprite.play()#順帶檢查角色是否移動,移動 else: $AnimatedSprite.stop() #$ 是get_node()的簡寫,所有在這裡,用$AnimatedSprite.play() 和get_node("AnimatedSprite").play()一樣 position += velocity * delta position.x = clamp(position.x, 0, screensize.x) position.y = clamp(position.y, 0, screensize.y) 未完待續