๐Ÿ“ฆ cart / godot3-bunnymark

๐Ÿ“„ BunnymarkV2.cs ยท 103 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

public class BunnymarkV2 : Node2D
{
    Vector2 screenSize;

    Texture bunnyTexture = (Texture)GD.Load("res://images/godot_bunny.png");
    List<Vector2> speeds = new List<Vector2>();
    Random random = new Random();
    int gravity = 500;
    Node2D bunnies = new Node2D();
    Label label = new Label();

    public override void _Ready()
    {
        AddChild(bunnies);
        label.RectPosition = new Vector2(0, 20);
        AddChild(label);
    }

    public override void _Process(float delta)
    {
        screenSize = GetViewportRect().Size;
        label.Text = $"Bunnies: {bunnies.GetChildCount()}";
        
        var bunnyChildren = bunnies.GetChildren();
        for (var i = 0; i < bunnyChildren.Count; i++)
        {
            var bunny = (Sprite)bunnyChildren[i];
            var position = bunny.Position;
            var speed = speeds[i];

            position.x += speed.x * delta;
            position.y += speed.y * delta;

            speed.y += gravity * delta;

            if (position.x > screenSize.x)
            {
                speed.x *= -1;
                position.x = screenSize.x;
            }

            if (position.x < 0)
            {
                speed.x *= -1;
                position.x = 0;
            }

            if (position.y > screenSize.y)
            {
                position.y = screenSize.y;
                if (random.NextDouble() > 0.5)
                {
                    speed.y = (random.Next() % 1100 + 50);
                }
                else
                {
                    speed.y *= -0.85f;
                }
            }

            if (position.y < 0)
            {
                speed.y = 0;
                position.y = 0;
            }

            bunny.Position = position;
            speeds[i] = speed;
        }
    }

    public void add_bunny()
    {
        var bunny = new Sprite();
        bunny.SetTexture(bunnyTexture);
        bunnies.AddChild(bunny);
        bunny.Position = new Vector2(screenSize.x / 2, screenSize.y / 2);
        speeds.Add(new Vector2(random.Next() % 200 + 50, random.Next() % 200 + 50));
    }

    public void remove_bunny()
    {
        var childCount = bunnies.GetChildCount();
        if (childCount == 0) {
			return;
		}

        var bunny = bunnies.GetChild(childCount - 1);
        speeds.RemoveAt(childCount - 1);
        bunnies.RemoveChild(bunny);
    }

    public void finish()
    {
        EmitSignal("benchmark_finished", bunnies.GetChildCount());
    }
}