Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Can you create a godot 4 based hockey game similar to that of NHL 94? It should use…

  1. User

    Can you create a godot 4 based hockey game similar to that of NHL 94? It should use sprite nodes for players that are spawned in along with a puck.

  2. Assistant

    Creating a 2D hockey game similar to NHL 94 in Godot 4 is an exciting project! Below is a step-by-step guide to help you get started. We'll cover setting up the project, creating player and puck sprites, handling movement, collisions, and basic game mechanics.

    1. Project Setup

    1. Install Godot 4: Ensure you have Godot 4 installed. You can download it from the official website.

    2. Create a New Project:

      • Open Godot.
      • Click on "New Project".
      • Choose a project path and name, e.g., HockeyGame.
      • Click "Create & Edit".

    2. Project Structure

    Organize your project with the following folder structure:

    HockeyGame/
    ├── assets/
    │   ├── players/
    │   ├── puck/
    │   └── arena/
    ├── scenes/
    │   ├── Main.tscn
    │   ├── Player.tscn
    │   └── Puck.tscn
    ├── scripts/
    │   ├── Player.gd
    │   ├── Puck.gd
    │   └── Game.gd
    └── ...
    

    3. Creating the Arena

    1. Import Arena Assets:

      • Design a simple rink layout or use a placeholder image.
      • Import it into assets/arena/.
    2. Create Arena Scene:

      • Right-click on scenes/ > New Scene.
      • Add a Sprite2D node.
      • Name it Arena.
      • In the Inspector, load your arena texture.
      • Save the scene as Arena.tscn.

    4. Creating Player Scene

    1. Create Player Scene:

      • Right-click on scenes/ > New Scene.
      • Add a CharacterBody2D node (suitable for player movement with physics).
      • Name it Player.
      • Add a Sprite2D as a child for the player’s visual representation.
      • Load a player sprite in the Sprite2D node.
    2. Add Collision:

      • Add a CollisionShape2D as a child of Player.
      • Choose a suitable shape (e.g., CircleShape2D) and adjust the size to fit the sprite.
    3. Attach Script:

      • Select the Player node.
      • Click Attach Script and name it Player.gd.
      • Use the following script as a starting point:
    # scripts/Player.gd
    extends CharacterBody2D
    
    # Player movement speed
    const SPEED = 200
    
    # Input mappings
    var velocity = Vector2.ZERO
    
    func _process(delta):
        velocity = Vector2.ZERO
    
        if Input.is_action_pressed("ui_right"):
            velocity.x += 1
        if Input.is_action_pressed("ui_left"):
            velocity.x -= 1
        if Input.is_action_pressed("ui_down"):
            velocity.y += 1
        if Input.is_action_pressed("ui_up"):
            velocity.y -= 1
    
        velocity = velocity.normalized() * SPEED
        move_and_slide()
    
    func set_player_direction(direction):
        $Sprite2D.rotation = direction.angle()
    
    1. Define Input Actions:

      • Go to Project > Project Settings > Input Map.
      • Add actions: ui_up, ui_down, ui_left, ui_right.
      • Assign keys (e.g., arrow keys or WASD).
    2. Save the Scene:

      • Save as Player.tscn.

    5. Creating the Puck Scene

    1. Create Puck Scene:

      • Right-click on scenes/ > New Scene.
      • Add a RigidBody2D node (for physics-based movement).
      • Name it Puck.
      • Add a Sprite2D as a child and load the puck sprite.
    2. Add Collision:

      • Add a CollisionShape2D as a child of Puck.
      • Use a CircleShape2D and adjust the size.
    3. Attach Script:

      • Select the Puck node.
      • Click Attach Script and name it Puck.gd.
      • Basic movement is handled by physics, but you can add custom behavior if needed.
    # scripts/Puck.gd
    extends RigidBody2D
    
    # Optionally, customize puck behavior
    func _ready():
        # Set puck to start moving
        apply_impulse(Vector2.ZERO, Vector2(randf_range(-100, 100), randf_range(-100, 100)))
    
    1. Save the Scene:
      • Save as Puck.tscn.

    6. Assembling the Main Scene

    1. Create Main Scene:

      • Right-click on scenes/ > New Scene.
      • Add a Node2D as the root and name it Main.
    2. Instance Arena:

      • Drag Arena.tscn into the Main scene.
    3. Instance Players:

      • Drag Player.tscn into the Main scene twice for two players.
      • Position them on opposite sides of the rink.
      • Optionally, assign different input schemes for each player.
    4. Instance Puck:

      • Drag Puck.tscn into the Main scene.
      • Position it at the center of the rink.
    5. Attach Game Script:

      • Select the Main node.
      • Click Attach Script and name it Game.gd.
      • Here's a basic setup to manage the game:
    # scripts/Game.gd
    extends Node2D
    
    @export var player_scene: PackedScene
    @export var puck_scene: PackedScene
    
    var players = []
    var puck
    
    func _ready():
        # Instance players
        var player1 = player_scene.instantiate()
        player1.position = Vector2(-100, 0)
        add_child(player1)
        players.append(player1)
    
        var player2 = player_scene.instantiate()
        player2.position = Vector2(100, 0)
        add_child(player2)
        players.append(player2)
    
        # Instance puck
        puck = puck_scene.instantiate()
        puck.position = Vector2(0, 0)
        add_child(puck)
    
    1. Configure Exported Variables:

      • Select the Main node.
      • In the Inspector, assign Player.tscn to player_scene and Puck.tscn to puck_scene.
    2. Save the Scene:

      • Save as Main.tscn.

    7. Setting Up the Main Scene as Entry Point

    1. Open Project Settings:
      • Go to Project > Project Settings > Run > Main Scene.
      • Click the folder icon and select Main.tscn.

    8. Adding Basic Controls and Movement

    The Player.gd script provided earlier handles basic movement. To handle two players with separate controls, you need to differentiate input for each player. Here's how:

    1. Modify Input Mappings:

      • Go to Project > Project Settings > Input Map.
      • Add additional actions for the second player, e.g., ui_up_p2, ui_down_p2, ui_left_p2, ui_right_p2.
    2. Update Player.gd to Handle Player Number:

    # scripts/Player.gd
    extends CharacterBody2D
    
    # Player movement speed
    const SPEED = 200
    
    # Player number (1 or 2)
    @export var player_number: int = 1
    
    var velocity = Vector2.ZERO
    
    func _process(delta):
        velocity = Vector2.ZERO
        
        var up_action = "ui_up"
        var down_action = "ui_down"
        var left_action = "ui_left"
        var right_action = "ui_right"
        
        # Adjust actions based on player number
        if player_number == 2:
            up_action = "ui_up_p2"
            down_action = "ui_down_p2"
            left_action = "ui_left_p2"
            right_action = "ui_right_p2"
        
        if Input.is_action_pressed(right_action):
            velocity.x += 1
        if Input.is_action_pressed(left_action):
            velocity.x -= 1
        if Input.is_action_pressed(down_action):
            velocity.y += 1
        if Input.is_action_pressed(up_action):
            velocity.y -= 1
    
        velocity = velocity.normalized() * SPEED
        velocity = move_and_slide(velocity)
    
    1. Assign Player Numbers in Game.gd:
    # scripts/Game.gd
    extends Node2D
    
    @export var player_scene: PackedScene
    @export var puck_scene: PackedScene
    
    var players = []
    var puck
    
    func _ready():
        # Instance player 1
        var player1 = player_scene.instantiate()
        player1.player_number = 1
        player1.position = Vector2(-100, 0)
        add_child(player1)
        players.append(player1)
    
        # Instance player 2
        var player2 = player_scene.instantiate()
        player2.player_number = 2
        player2.position = Vector2(100, 0)
        add_child(player2)
        players.append(player2)
    
        # Instance puck
        puck = puck_scene.instantiate()
        puck.position = Vector2(0, 0)
        add_child(puck)
    

    9. Handling Collisions and Puck Movement

    1. Ensure Collision Layers and Masks:

      • For each Player and the Puck, ensure their collision layers and masks are set appropriately to detect collisions.
      • Example:
        • Players: Layer 1, Mask 1 (detecting puck and other players).
        • Puck: Layer 2, Mask 1 (detecting players).
    2. Add Collision Handling:

      • In the Puck.gd script, you can handle collisions for scoring or puck behavior.
    # scripts/Puck.gd
    extends RigidBody2D
    
    func _on_Puck_body_entered(body):
        if body.name.begins_with("Player"):
            # Apply impulse or handle puck-player interaction
            pass
        elif body.name == "GoalArea":
            # Handle scoring
            pass
    
    func _ready():
        connect("body_entered", self, "_on_Puck_body_entered")
    
    1. Add Goals:
      • Create goal areas using Area2D nodes with CollisionShape2D.
      • Detect when the puck enters these areas to increment scores.

    10. Basic Scoring and UI

    1. Create UI Elements:

      • Add a CanvasLayer node to the Main scene for UI.
      • Add Label nodes for displaying scores.
    2. Update Scores:

      • In Game.gd, keep track of scores and update the labels when goals are scored.
    # scripts/Game.gd
    extends Node2D
    
    @export var player_scene: PackedScene
    @export var puck_scene: PackedScene
    
    var players = []
    var puck
    var score_player1 = 0
    var score_player2 = 0
    
    @onready var score_label_p1 = $CanvasLayer/ScorePlayer1
    @onready var score_label_p2 = $CanvasLayer/ScorePlayer2
    
    func _ready():
        # Instance players and puck as before
        # Connect puck signal
        puck.connect("goal_scored", self, "_on_goal_scored")
    
    func _on_goal_scored(player_scored: int):
        if player_scored == 1:
            score_player1 += 1
        elif player_scored == 2:
            score_player2 += 1
        update_score_labels()
        reset_positions()
    
    func update_score_labels():
        score_label_p1.text = str(score_player1)
        score_label_p2.text = str(score_player2)
    
    func reset_positions():
        # Reset puck and players to starting positions
        puck.position = Vector2(0, 0)
        for i, player in players:
            if i == 0:
                player.position = Vector2(-100, 0)
            elif i == 1:
                player.position = Vector2(100, 0)
    
    1. Modify Puck.gd to Emit a Signal on Goal:
    # scripts/Puck.gd
    extends RigidBody2D
    
    signal goal_scored(player)
    
    func _on_Puck_body_entered(body):
        if body.name == "GoalAreaPlayer1":
            emit_signal("goal_scored", 2) # Player 2 scores
        elif body.name == "GoalAreaPlayer2":
            emit_signal("goal_scored", 1) # Player 1 scores
    
    func _ready():
        connect("body_entered", self, "_on_Puck_body_entered")
    

    11. Adding Camera and UI Polish

    1. Camera:

      • Add a Camera2D node to the Main scene.
      • Set it to follow the puck or players for dynamic view.
    2. Polish Sprites:

      • Design or import better sprites for players, puck, and arena.
      • Add animations if desired for actions like shooting or checking.
    3. Physics Tuning:

      • Adjust physics parameters such as friction, bounce, and mass for realistic puck behavior.

    12. Testing and Iteration

    1. Run the Game:

      • Press F5 to run the game.
      • Test player movements, puck interactions, and scoring.
    2. Debugging:

      • Use Godot’s debugger to fix any issues.
      • Adjust scripts and scene setups as needed.
    3. Iterate:

      • Enhance gameplay by adding features like power-ups, AI opponents, sound effects, and more refined controls.

    Sample Project Repository

    For a complete reference, consider looking at this simple Godot hockey example, which includes player movement, puck physics, and basic scoring. (Note: Replace with an actual repository if available.)

    Further Resources

    Final Tips

    • Start Simple: Focus on core mechanics before adding complex features.
    • Use Godot’s Scene System: Leverage instancing and reusable scenes for players and puck.
    • Optimize Performance: Keep sprite sizes manageable and optimize scripts.
    • Community Help: Engage with the Godot community for support and feedback.

    Good luck with your hockey game development in Godot 4! If you encounter specific issues or need further assistance, feel free to ask.