Godot 4.1 C# 打地鼠游戏教程:随机出现和频率变化
Godot 4.1 C# 打地鼠游戏教程:随机出现和频率变化
想学习如何在 Godot 4.1 中使用 C# 创建一个打地鼠游戏吗?这篇教程将带你逐步完成整个过程!我们将涵盖以下内容:
- 设置游戏场景- 随机生成地鼠- 随着时间推移增加出现频率- 处理玩家点击
1. 设置游戏场景
首先,在 Godot 编辑器中创建一个新场景,命名为 'WhackAMole'。 添加一个 Sprite 节点作为背景,并创建一个新的 C# 脚本,命名为 'WhackAMole.cs' 并将其附加到根节点。
2. 创建地鼠场景
创建一个新的场景,命名为 'Mole',并添加一个 Sprite 节点来表示地鼠。 创建一个名为 'Mole.cs' 的 C# 脚本并将其附加到 'Mole' 节点。
3. 编写 C# 代码
WhackAMole.cscsharpusing Godot;using System;
public class WhackAMole : Node2D{ private Timer timer; private PackedScene moleScene; private Random random; private int moleSpawnMinDelay = 1000; private int moleSpawnMaxDelay = 3000; private float moleSpawnRate = 1f;
public override void _Ready() { timer = GetNode<Timer>('Timer'); moleScene = (PackedScene)ResourceLoader.Load('res://Mole.tscn'); random = new Random();
timer.Connect('timeout', this, nameof(OnTimerTimeout)); timer.WaitTime = GetRandomSpawnDelay(); timer.Start(); }
private void OnTimerTimeout() { SpawnMole(); timer.WaitTime = GetRandomSpawnDelay(); timer.Start(); }
private void SpawnMole() { var newMole = (Mole)moleScene.Instance(); AddChild(newMole);
var screenSize = GetViewport().Size; var spawnPosition = new Vector2(random.Next((int)screenSize.x), random.Next((int)screenSize.y)); newMole.Position = spawnPosition; }
private float GetRandomSpawnDelay() { // 根据当前的地鼠生成速率,计算出下一个地鼠出现的间隔时间 float spawnDelay = (float)((moleSpawnMaxDelay - moleSpawnMinDelay) * Math.Pow(0.9, moleSpawnRate)) + moleSpawnMinDelay; moleSpawnRate += 0.1f; return spawnDelay / 1000f; // 将毫秒转换为秒 }
public void IncreaseScore() { // 这里处理分数增加逻辑 }}
Mole.cscsharpusing Godot;
public class Mole : Area2D{ private AnimationPlayer animationPlayer; private WhackAMole game;
public override void _Ready() { animationPlayer = GetNode<AnimationPlayer>('AnimationPlayer'); game = GetTree().Root.GetNode<WhackAMole>('WhackAMole');
Connect('input_event', this, nameof(OnMoleInputEvent)); animationPlayer.Play('Idle'); // 替换为你的地鼠闲置动画名称 }
private void OnMoleInputEvent(Node camera, InputEvent inputEvent, Vector3 clickPosition, Vector3 clickNormal, int shapeIdx) { if (inputEvent is InputEventMouseButton mouseButton && mouseButton.Pressed && mouseButton.ButtonIndex == (int)ButtonList.Left) { animationPlayer.Play('Whacked'); // 替换为你的地鼠被击中动画名称 game.IncreaseScore(); QueueFree(); }
原文地址: https://www.cveoy.top/t/topic/PI5 著作权归作者所有。请勿转载和采集!