GodotEngine游戏引擎上的Platformer实现机制

您好,我已经在Godot Engine上开发游戏大约2年了,所以我决定创建一个程序代码集合来实现基本的平台机制。该系列专为使用Godot引擎的新用户而设计。



是的,将提供指向后续文章的更多链接。



基本代码



为了使角色服从物理学,您需要在_process()或_physics_process()方法中调用move_and_slide()。



在下面的代码中,我将使用静态类型。



extends KinematicBody2D
#     gdscript   ,    python

var velocity: Vector2 = Vector2.ZERO 	#   .
					#     
					#   

func _physics_process(_delta: float) -> void:
	#     
	
	
	self.velocity = self.move_and_slide(self.velocity, Vector2(0, -1)) 
	#        .
	#   -  ,    .
	#      .


此代码足以使任何KinematicBody2D对象根据与其他对象的碰撞而移动,但是无法控制该对象,尤其是在平台游戏中,该对象仍然无法掉落。为了使物体开始下降,您需要将self.velocity.y的值增加一个正值。事实是Godot Engine在2D模式下从左上角到右下角计算两个坐标。为了使物体掉落,您需要向加速度添加一些东西。我通常使用GRAVITY常数,该常数在程序开始时给出。接下来,将对代码进行更改,以使对象掉落。



extends KinematicBody2D

const GRAVITY: int = 40
#    40   ,     


var velocity: Vector2 = Vector2.ZERO 	#  


func _physics_process(_delta: float) -> void:
	#     

	#     
	self.velocity.y += GRAVITY
	#   _delta  ,     self.move_and collide
	self.velocity = self.move_and_slide(self.velocity, Vector2(0, -1))
	#  ,      .    .


移动控制应以单独的方法实现,以免使一种方法过于复杂。而且,没有人能承受一则文章中相同代码的重复33次。



移动



我最近学习了一种有趣的方式来控制角色,这成为了我掌握的第一种方法的替代方法。接下来,我将展示两种方法:



  • 我的第一种新方法
  • func move_character() -> void:
    	var direction: float = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left") 
    	#         
    	#  (+  x,  0  1)  (-  x,  0  1).
    	#   = 0,   < 0  ,     
    	# ,    .
    	self.velocity.x = direction * MOVE_SPEED #   .
    #  const MOVE_SPEED = #      const GRAVITY
    
  • 第二种方式
  • func move_character() -> void: #  
    	var direction: float = 0
    	if Input.is_action_pressed("ui_left"):
    		direction = -1
    	elif Input.is_action_pressed("ui_right"):
    		direction = 1
    	else:
    		direction = 0
    	self.velocity.x = direction * MOVE_SPEED
    #  const MOVE_SPEED = #   #  const GRAVITY
    


弹跳



几乎与第一种移动方法一样轻松而明确地实现了跳跃。为此,您需要创建一个跳跃力常数,作为开始时的运动速度,并设置一个大于重力值的值。让我们直接进入程序代码:



func jump() -> void:
	if self.is_on_floor(): # ,    .
	#     ,      
		if Input.is_action_pressed("ui_jump"): #    
				#  ui_jump      .
				#   "ui_up"
			self.velocity.y -= JUMP_POWER
# const JUMP_POWER...          


剩下的只是绘制地图,添加碰撞以及与主代码不直接相关的其他事情,对于游戏角色,最终可以通过这些位置安排一次奔跑,但是大约还有一次,因为到目前为止,我还没有弄清楚如何更正确地解释其他代码片段,这超出了消息的范围。



All Articles