Godot 4.1 C# 打地鼠游戏开发教程:随机出现、频率可调

本教程将手把手教你使用 C# 在 Godot 4.1 中开发一款简单的打地鼠游戏,无需音乐和计数器。地鼠将随机出现,且出现频率可以随时间变化。

第一步:创建场景和脚本

  1. 在 Godot 编辑器中创建一个新的场景,命名为'WhackAMole',并创建一个 2D 节点作为根节点。
  2. 在根节点下添加一个 Sprite 节点作为背景,用来显示游戏场景。
  3. 创建一个名为'WhackAMole.cs' 的脚本,并将其附加到根节点上。
using Godot;
using System;

public class WhackAMole : Node2D
{
    private Timer timer;
    private PackedScene moleScene;
    private Random random;
    
    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.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()
    {
        // 随机产生一个出现间隔时间,例如 0.5 到 2 秒之间
        return (float)random.NextDouble() * 1.5f + 0.5f;
    }
}

第二步:创建地鼠场景和脚本

  1. 创建一个新的场景,命名为'Mole',并在其中添加一个 Sprite 节点用来显示地鼠的图像。
  2. 创建一个名为'Mole.cs' 的脚本,并将其附加到'Mole' 节点上。
using Godot;

public class Mole : Area2D
{
    private AnimationPlayer animationPlayer;
    
    public override void _Ready()
    {
        animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
        
        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");
            // 地鼠被点击时的逻辑
            QueueFree();
        }
    }
}

第三步:整合场景和资源

  1. 在 Godot 编辑器中,将'Mole' 场景作为一个资源导入到主场景'WhackAMole' 中。

第四步:运行游戏

  1. 运行游戏,你将看到地鼠会随机出现在屏幕上,点击它们,它们就会消失。

注意:

  • 以上代码示例仅包含基本的逻辑,你可以根据自己的需求进行扩展和修改。
  • 为了方便理解,代码中的双引号已改为单引号。
  • 你需要添加一个计时器节点(Timer)到主场景,并将其命名为“Timer”。
  • 你还需要为地鼠添加一个动画播放器节点(AnimationPlayer),并添加两个动画:'Idle'(地鼠静止)和 'Whacked'(地鼠被点击)。
  • 为了使游戏更有趣,你可以添加计分器、游戏结束提示等功能。
  • 请根据自己的实际情况修改代码和资源。

祝你开发顺利!

Godot 4.1 C# 打地鼠游戏开发教程:随机出现、频率可调

原文地址: https://www.cveoy.top/t/topic/PIE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录