Menu
CoddyTech

射击小行星

本课属于 Coddy Godot 学习旅程的“项目”单元。第 17 课,共 36 课。

岩石是一个 Area2D,子弹是一个物理体,所以 body_entered 会在子弹击中岩石时通知它。每颗子弹都属于 bullets 组。

func _on_body_entered(body):
	if body.is_in_group("bullets"):
		body.queue_free()
		burst()
		queue_free()

也要移除子弹。否则它会继续飞行,击碎后面的岩石。burst() 已经写在 rock.gd 中。它会在岩石所在的位置扬起一团尘土。请在 queue_free() 之前调用它。

challenge icon

挑战

中等

让子弹击碎岩石。

  1. 在 rock.gd 中,在 _ready 里将 body_entered 连接到 _on_body_entered。
  2. 当物体属于 bullets 组时,移除子弹,调用 burst(),然后移除岩石。

按“开始”并向岩石射击:它会爆成尘埃。然后点击“检查”。

亲手试试

extends Area2D

var velocity = Vector2.ZERO

func _physics_process(delta):
	position += velocity * delta
	rotation += 0.5 * delta
	if position.x < -30:
		position.x += 700
	if position.x > 670:
		position.x -= 700
	if position.y < -30:
		position.y += 420
	if position.y > 390:
		position.y -= 420

# Bursts into dust where the rock is. Call it when the rock breaks.
func burst():
	var dust = CPUParticles2D.new()
	dust.position = position
	dust.one_shot = true
	dust.explosiveness = 1.0
	dust.amount = 20
	dust.lifetime = 0.7
	dust.spread = 180.0
	dust.gravity = Vector2.ZERO
	dust.initial_velocity_min = 30.0
	dust.initial_velocity_max = 120.0 * scale.x
	dust.scale_amount_min = 2.0
	dust.scale_amount_max = 5.0
	dust.color = Color(0.75, 0.82, 0.95)
	dust.finished.connect(dust.queue_free)
	get_parent().add_child(dust)
	dust.emitting = true

项目中的所有课

自己练习: Godot 在线编辑器