I'm creating a game where the player will be able to swap between 2d and 2.5D and need a way to be able to apply gravity when you are in 2d but not when in the 25d plane. also help me figure out some cool mechanic to be able to dodge attacks by swapping plane, it will be a rougelike/bullet hell game
Assistant
Creating a game that allows the player to swap between 2D and 2.5D presents some unique challenges but also opportunities for innovative gameplay mechanics. Below, I'll outline one approach to handling gravity and dodging attacks through plane swapping in the context of a rogue-like/bullet hell game.
Gravity Handling:
Create a Gravity Component/System: Implement a gravity component or system that applies a downward force on the player when in the 2D plane. This could be a part of a physics engine you are using or a custom script that alters the player's velocity or position over time.
Toggle Gravity Based on Plane: Set up a toggle or flag that gets triggered when the player switches between planes. When the player is in 2D mode, enable gravity by applying the downward force. When the player swaps to 2.5D, disable gravity by stopping the application of this force.
pseudo
if (currentPlane == PlaneType.TwoD) {
enableGravity();
} else if (currentPlane == PlaneType.TwoPointFiveD) {
disableGravity();
}
Anchor Point in 2.5D: When the player switches to 2.5D, depending on how you envision this plane, gravity might still exist but not affect the player significantly. Make sure the player has some kind of anchor or is locked in position on the Y-axis (up-down) to avoid falling due to residual dynamics when they swing back to 2D.
Dodge Mechanic Using Plane Swap:
Plane-Specific Colliders: Enemies and bullets should have colliders that only interact with the player’s collider when they are in the same plane. This means that when in 2.5D, bullets that are designed to hit in 2D would simply pass by without interaction.
Cool Down: To avoid constant plane swapping making the player invincible, implement a cooldown system that only lets the player change planes after a certain interval or under specific conditions.
Visual Clues: Give visual indicators for attacks that are tied to each plane so players can plan their dodge by swapping accordingly. For example, bullets meant for the 2D plane could have a distinct look or color scheme compared to those in 2.5D.
Swap Animation: Create a swapping animation that briefly makes the player invulnerable but can't be repeatedly spammed. This is when the player is neither in 2D nor 2.5D but in transition, granting them a moment to escape a fatal bullet pattern.
Strategic Positioning: Encourage players to consider their position before swapping planes. For instance, swapping to 2.5D could place the player behind an obstacle in the new plane, providing coverage from incoming attacks.
Swap Momentum: Maintain the player’s momentum when they switch planes. If they’re moving when they swap, they should still be moving in the same direction afterward, which can be used to dodge strategically.
Selective Interaction: Design some enemy attacks that can reach into both planes with a clear tell so the player knows a simple plane swap won't suffice, and they must move to dodge.
Energy Resource: Linking the plane swap to an energy meter that recharges over time can make dodging a resource-based strategy, adding depth to the gameplay.
Keep in mind that game design is a process of iteration and testing. You’ll likely need to adjust these mechanics as you see how they interact with the rest of your gameplay. The key to a compelling rogue-like/bullet hell game often lies in creating a balanced challenge that rewards skill and strategy, while still feeling fair to the player. Good luck with your game development!
User
this is my player script:
extends Entity
class_name Player25D
enum State { IDLE, RUN, JUMP, ATTACK }
var attack_animation: String = "Attack1"
@onready var animator : AnimatedSprite2D = AnimatedSprite2D@onreadyvarhand:Hand
@onready var muzzle_load: PackedScene = preload("res://Scenes/Particles/muzzle.tscn")
@onready var bullet_load: PackedScene = preload("res://Scenes/Props/bullet.tscn")
@onready var pistol_bullet_marker : Marker2D = ShootingAnimationPlayer
var state = State.IDLE
var gold : int = 0
var crystals : int = 0
Assistant
It looks like you have the beginning of a game script outlined using the Godot Engine scripting language, GDScript. However, several improvements and changes can be made to implement the mechanics you're looking for. Below are suggestions and modifications to integrate gravity control and dimensional swapping for dodging.
Player25D Script Changes
Modify your _physics_process function to handle gravity based on the plane:
gdscript
func _physics_process(delta):
super._physics_process(delta)
if current_plane == "2D":
apply_gravity(delta)
elif current_plane == "25D":
# Optionally lock Y position or apply 2.5D specific physics
# Other physics handling
Define a swap_plane flag, which is false initially and will become true whenever the plane is changed:
gdscript
var swap_plane = false
Modify your _on_swapPlane function to use the flag:
gdscript
func _on_swapPlane():
swap_plane = true
PlayerState.set_last_2d_position(global_position)
if current_plane == "2D":
current_plane = "25D"
SceneChanger.change_to_25d(global_position) # Calls the function to change to 2.5D scene
else:
current_plane = "2D"
SceneChanger.change_to_2d(global_position) # Calls the function to change to 2D scene
yield(get_tree().create_timer(cooldown_duration), "timeout") # Assuming you have some sort of cooldown
swap_plane = false
Make sure your apply_gravity function is only called when in 2D mode:
gdscript
func apply_gravity(delta):
if current_plane == "2D":
velocity.y += gravity * delta
move_and_slide(velocity)
if is_on_floor():
velocity.y = 0
User
how can I make so the ui is always loaded so I don't need to add it to all the scenes?
Assistant
In Godot, you can have persistent UI elements that do not need to be added to each scene individually by using autoloaded (singleton) nodes. This is especially useful for elements like HUDs, score displays, and other global interfaces that should remain consistent and visible across various scenes.
Here's how you can make your UI persist across scenes:
Create the UI Scene: First, create a scene for your UI elements. This should be its own standalone scene, something like HUD.tscn or UI.tscn, which contains all the elements you want to be available universally.
Autoload the UI Scene: After you've created your scene, you can set it as an autoloaded scene to make it automatically load when your game starts and persist across scene changes.
To autoload a scene in Godot:
Go to the "Project" menu and select "Project Settings."
Navigate to the "Autoload" tab.
Click the folder icon to the right of the "Path" field, and select your UI scene (e.g., HUD.tscn).
In the "Node Name" field, give the node a name that you'll use to reference it in code (e.g., HUD).
Press "Add" to add the scene to the autoload list.
Accessing the UI Script: After the UI scene is autoloaded, it becomes a singleton that you can access from any script using its node name. For example, if you name your autoloaded UI scene HUD, you can access it as follows:
gdscript
HUD.update_score(10) # Assuming you have an `update_score` method in your HUD script
Consistent UI across Scenes: Because the UI is autoloaded, it will now persist across scene changes. You don't have to manually add it to other scenes.
Layer Order: Since UI elements typically need to draw over other game elements, ensure your UI scene is added to a CanvasLayer with a higher layer index than the rest of your game elements.
Show/Hide Based on Context: Sometimes you might want specific elements of the UI to only be visible in certain conditions, so make sure to include functionality in your UI script to hide or show different parts of the UI as necessary.
By using this approach, you ensure your UI is always loaded and stays on top of other elements, no matter which scene is currently active. Remember, you can still communicate between the autoloaded HUD/UI and current active scenes using signals or direct function calls.
Keep in mind to also respect the game's flow and hide the UI when it's not needed, like during cutscenes or in menus to avoid cluttering the player's view unnecessarily.
User
how to stop this:
func _physics_process(delta):
move_and_slide()
var collision = get_last_slide_collision()
if(collision && collision.get_collider()):
var collider = collision.get_collider()
code
if collider.get_groups().size() && collider.get_groups().has("entity"):
var enemy_group = controller.get_enemy_group()
if collider.get_groups().size() && collider.get_groups().has(enemy_group):
collider.apply_damage(damage)
print(collider.current_health)
_explode()
from following me when I swap scene?
Assistant
In Godot Engine, if a process like _physics_process is continuing to execute after you've swapped a scene, it usually means that the object running the process has not been properly freed or that the game logic does not account for the change in scenes.
Here's what you can do to ensure that the process stops when you change scenes:
Deactivate the Node: If you are switching scenes and you want certain nodes to stop their physics processing, you can deactivate them before the switch. Set the processing property to false to stop _physics_process from being called:
gdscript
func before_scene_swap():
self.set_physics_process(false)
# Any other cleanup code here
Queue Free: Ensure that you free nodes that should not exist after a scene swap. To free a node safely, which also ensures it won’t process any further events or physics, use:
gdscript
func before_scene_swap():
self.queue_free()
Check for Validity: If your object needs to persist between scenes (for example, an autoloaded singleton), but you want certain processes to stop, you should add a condition check to see if it should continue processing based on the current state of the game:
gdscript
func _physics_process(delta):
if current_scene_name == "TheSceneIWantToProcessIn":
move_and_slide()
# Rest of your code
Disconnect Signals: If the process involves reacting to signals, ensure you disconnect these signals when swapping scenes:
Verify Node Deletion: If you are calling change_to_2d or change_to_25d to swap entire scenes (with get_tree().change_scene()), make sure nodes from the previous scene are actually getting freed. Otherwise, this might indicate that they are still somehow referenced in your running code.
Assistant
It seems like your message didn't come through. Could you please provide more details or clarify your question so I can assist you further?
User
when you move left and right the gravity doesn't aåpply:
func interact():
var c = _get_collisions()
if c && (c.get_groups().size() && c.get_groups().has("interactable")): c.interact()
var facing_direction = 1 # 1 for right, -1 for left
func _read_input():
var mouse_position: Vector2 = (get_global_mouse_position() - global_position).normalized()
animator.flip_h = mouse_position.x < 0
var movement = []
state = State.IDLE
hand.rotation = mouse_position.angle()
if hand.scale.y == 1 and mouse_position.x < 0:
hand.scale.y = -1
elif hand.scale.y == -1 and mouse_position.x > 0:
hand.scale.y = 1
code
if Input.is_action_pressed("move_up"):
movement.append("up")
state = State.RUN
if Input.is_action_pressed("move_down"):
movement.append("down")
state = State.RUN
if Input.is_action_pressed("move_right"):
movement.append("right")
state = State.RUN
if Input.is_action_pressed("move_left"):
movement.append("left")
state = State.RUN
if Input.is_action_just_pressed("jump"):
movement.append("jump")
state = State.RUN
if movement:
move.execute(self, movement)
if last_ability > global_cooldown:
if Input.is_action_just_pressed("interact"):
interact()
last_ability = 0
if Input.is_action_just_pressed("SwapPlane"):
_on_swapPlane()
last_ability = 0
#if Input.is_action_just_pressed("shoot"):
# perform_attack()
if Input.is_action_pressed("shoot"):
swordslash.execute(self, mouse_position)
last_ability = 0
sword.play("Attack")
#if Input.is_action_just_pressed("inventory"):
# inventory.execute(self)
# last_ability = 0
if state == State.RUN:
animator.play("Run")
else:
animator.play("Idle")
func apply_gravity(delta):
# Apply gravity to the player’s velocity
if GameManager.current_plane == "2D":
# Apply gravity to the player’s velocity
velocity.y += gravity * delta
code
# Move the player and process collisions
if self is CharacterBody2D:
# Assuming you have a floor_normal set up correctly and a max_slides value
move_and_slide()
# You can reset y velocity if on the floor
if is_on_floor():
velocity.y = 0
velocity.x = 0
else:
# If the entity is not a KinematicBody2D, you’ll need another way to apply velocity.
# It will depend on how your Entity class handles physics and movement.
pass
func _physics_process(delta):
last_ability += 1
if has_gravity:
apply_gravity(delta)
if ((GameManager.count % 60) == 0):
regen_health()
regen_mana()
Assistant
If gravity is not applying when you move left and right, it may be due to the move_and_slide method being called without the appropriate velocity or parameters. Additionally, the function apply_gravity seems to be overridden by a later definition that does not include the lateral movement code.
Here's what you can do to fix this:
Ensure movement and gravity are applied together: You must apply both the lateral movement and gravity within the same _physics_process function to ensure the character moves correctly in all directions while also being affected by gravity.
Accumulate Horizontal Velocity: Keep track of horizontal velocity separately, then apply it along with gravity.
Here's how the relevant part of your code could be updated:
gdscript
var velocity: Vector2 = Vector2() # Store the player's velocity
func apply_gravity(delta):
if GameManager.current_plane == "2D":
velocity.y += gravity * delta
if is_on_floor():
velocity.y = 0
# Accumulate horizontal velocity based on input
func get_input():
var move_speed = 100 # Replace with your movement speed
if Input.is_action_pressed("move_right"):
velocity.x = move_speed
elif Input.is_action_pressed("move_left"):
velocity.x = -move_speed
else:
velocity.x = 0
func _physics_process(delta):
last_ability += 1
get_input() # Get the input and set horizontal velocity
if GameManager.current_plane == "2D":
apply_gravity(delta)
# Now move using both the horizontal and vertical velocity vectors
if self is CharacterBody2D:
move_and_slide(velocity, Vector2.UP)
if ((GameManager.count % 60) == 0):
regen_health()
regen_mana()
In this updated code, the lateral movement based on input is accumulated into the velocity.x, and gravity is applied to velocity.y. Both axes of the velocity vector are then used in move_and_slide. Remember to pass an up-direction vector (e.g., Vector2.UP—this is important) if the platform is considered "the floor" to ensure proper collision detection when the player is on the ground.
Lastly, there may be instances of code execution that relate to game state. For example, the gravity application should only happen if the player is in the 2D plane, as you have done. Ensure all your game state checks are correctly implemented and that the logic is consistent with the design of your game.
User
add one for gravity here:
extends Node2D
Called when the node enters the scene tree for the first time.
func execute(s, dir = []):
s.velocity = Vector2(0,0)
code
if dir.has("up"):
s.velocity.y -= 1
if dir.has("down"):
s.velocity.y += 1
if dir.has("left"):
s.velocity.x -= 1
if dir.has("right"):
s.velocity.x += 1
if dir.has("jump"):
s.velocity.y -= 5
if dir.size():
s.velocity = s.velocity * s.current_speed
s.velocity.normalized()
s.move_and_slide()
Assistant
To add gravity to your movement script, you'll need to make a few changes. Your move ability script currently sets the velocity to zero and then applies directional movement without considering ongoing momentum or physics forces like gravity. To integrate gravity, follow these steps:
Don't reset velocity to zero at the beginning of each execute call, as this will overwrite any existing vertical velocity due to gravity.
Apply gravity outside of the execute function since gravity should constantly affect the player entity.
Use move_and_slide with the linear_velocity parameter to handle collisions properly.
Include an apply_gravity method in your player script to consistently apply gravity when in 2D mode.
Let's first modify the execute function to remove the velocity reset and handle jumping:
gdscript
# Node2D
func execute(s, dir = []):
if dir.has("up"):
s.velocity.y -= 1
if dir.has("down"):
s.velocity.y += 1
if dir.has("left"):
s.velocity.x -= 1
if dir.has("right"):
s.velocity.x += 1
# Here we assume that the player script has an "is_jumping" state
if dir.has("jump") and s.is_on_floor():
s.is_jumping = true
s.velocity.y -= s.jump_strength # jump_strength is a hypothetical variable for jump power
if dir.size():
if s.is_jumping and s.is_on_floor():
s.is_jumping = false
s.velocity = s.velocity.normalized() * s.current_speed
s.move_and_slide(s.velocity, Vector2.UP)
else:
s.velocity.x = 0 # Stop horizontal movement if no input (optional)
Next, the player's _physics_process function should look something like this to apply gravity continuously:
var move = load_ability("move")
var swordslash = load_ability("swordslash")
func _get_collisions():
var c = get_last_slide_collision()
if (c && c.get_collider()): return c.get_collider()
else: return null
func interact():
var c = _get_collisions()
if c && (c.get_groups().size() && c.get_groups().has("interactable")): c.interact()
var facing_direction = 1 # 1 for right, -1 for left
func _read_input():
var mouse_position: Vector2 = (get_global_mouse_position() - global_position).normalized()
animator.flip_h = mouse_position.x < 0
var movement = []
state = State.IDLE
hand.rotation = mouse_position.angle()
if hand.scale.y == 1 and mouse_position.x < 0:
hand.scale.y = -1
elif hand.scale.y == -1 and mouse_position.x > 0:
hand.scale.y = 1
code
if Input.is_action_pressed("move_up"):
movement.append("up")
state = State.RUN
if Input.is_action_pressed("move_down"):
movement.append("down")
state = State.RUN
if Input.is_action_pressed("move_right"):
movement.append("right")
state = State.RUN
if Input.is_action_pressed("move_left"):
movement.append("left")
state = State.RUN
if Input.is_action_just_pressed("jump"):
movement.append("jump")
state = State.RUN
if movement:
move.execute(self, movement)
if last_ability > global_cooldown:
if Input.is_action_just_pressed("interact"):
interact()
last_ability = 0
if Input.is_action_just_pressed("SwapPlane"):
_on_swapPlane()
last_ability = 0
#if Input.is_action_just_pressed("shoot"):
# perform_attack()
if Input.is_action_pressed("shoot"):
swordslash.execute(self, mouse_position)
last_ability = 0
sword.play("Attack")
#if Input.is_action_just_pressed("inventory"):
# inventory.execute(self)
# last_ability = 0
if state == State.RUN:
animator.play("Run")
else:
animator.play("Idle")
func _on_swapPlane():
PlayerState.set_last_2d_position(global_position);
if(current_plane == "2D"):
current_plane = "25D"
SceneChanger.change_to_25d(global_position) # Calls the singleton to change to 3D scene
else:
current_plane = "2D"
SceneChanger.change_to_2d(global_position) # Calls the singleton to change to 3D scene
this is my entity script:
extends CharacterBody2D
class_name Entity
#var death_scene =
var death_config = {}
var direction : Vector2 = Vector2()
var max_health = 10
var current_health : int = 10
var health_regen : int = 1
var armor : int = 0
var max_mana : int = 100
var current_mana : int = 100
var mana_regen : int = 1
var max_speed : float = 100
var current_speed : float = 100
var acceleration : float = 4
var agility : int = 1
var global_cooldown = 30
var is_busy : bool = false
var last_ability : int = 0
var is_player : bool = false
var is_aliv : bool = true
var current_plane = "2D"
var gravity: float = 98.0 # Adjust the gravity force as needed
func apply_gravity(delta):
# Apply gravity to the player’s velocity
velocity.y += gravity * delta
code
# Move the player and process collisions
if self is CharacterBody2D:
# Assuming you have a floor_normal set up correctly and a max_slides value
move_and_slide()
# You can reset y velocity if on the floor
if is_on_floor():
velocity.y = 0
velocity.x = 0
else:
# If the entity is not a KinematicBody2D, you’ll need another way to apply velocity.
# It will depend on how your Entity class handles physics and movement.
pass
and game manager:
extends Node
var count : int = 0;
var player_node = null
var hud_node = null
var is_player_spawned = false
func get_current_player():
if (player_node): return player_node
else: return null
pass
var player = load("res://Scenes/Characters/Player/player25D.tscn")
player_node = player.instantiate()
player_node.is_player = true
var pos_x = 150
var pos_y = 70
player_node.position = Vector2(pos_x, pos_y)
var camera = Camera2D.new()
camera.is_current()
camera.zoom = Vector2(1, 1)
add_child(player_node)
player_node.add_child(camera)
#var hud = load("res://Scenes/UI/health_bar.tscn")
#hud_node = hud.instantiate()
#player_node.add_child(hud_node)
is_player_spawned = true
return player_node
pass
func _physics_process(delta):
count += 1
pass
func _ready():
pass
Add input handling for swapping in _read_input:
gdscript
if Input.is_action_just_pressed("swap_plane") and not swap_plane:
_on_swapPlane()
Entity Script Changes
You have a placeholder in apply_gravity, which needs to be filled with correct implementation. It is already inside _physics_process, but you need to ensure that gravity is only applied in 2D.
Make sure your move_and_slide includes the up vector for 2D and adjust max_slide if needed. Also, velocity.x should not be set to 0 in apply_gravity; it's probably meant to reset velocity.y to 0.
gdscript
func apply_gravity(delta):
if current_plane == "2D":
velocity.y += gravity * delta
move_and_slide(velocity, Vector2.UP)
if is_on_floor():
velocity.y = 0
GameManager Script Changes
With the current design of your GameManager, most of its purpose seems to be managing counts and spawning the player. Consider placing plane swapping management, global gravity settings, and cooldown timers within GameManager for better control from a single point.
Lastly, to enhance the plane swapping mechanic, consider the following suggestions:
Visual Feedback: Give visual cues during the swap to let the player know something significant is happening — a change in lighting, GUI indicators, sound effects, etc.
Invulnerability Window: Assign a short period during the swap where the player is invulnerable to provide a reliable way to avoid damage.
Swap Momentum: Preserve the player's momentum but potentially alter it depending on the plane they swap to, which could affect how they must aim or avoid obstacles.
Remember: Game design involves a lot of playtesting and iteration. Implement changes incrementally and test to ensure each mechanic is fun and works well within the context of your game. Don't be afraid to adapt these suggested changes to suit the particular needs and style of your game.
Cleanup on Scene Exit: You can override the _exit_tree method of your node, which is called when the node is removed from the scene tree, to perform any necessary cleanup:
gdscript
func _exit_tree():
self.set_physics_process(false) # Stop processing
# Any other cleanup needed before the node exits the scene
Monitor Autoloaded Nodes: If your object is an autoloaded singleton, it won't be freed on a scene change. You must manually control its behavior when scenes change.
Lastly, it’s vital to use the scene management functions correctly. If you’re using change_scene() (from SceneTree), the current scene will be cleared, and all nodes within it should be freed. If they’re not, the reason might be they are autoloaded or have been moved to the root node’s tree manually, and you will need to manage their lifecycle directly.
These steps should ensure that the process doesn't continue to execute after you've swapped scenes. Always remember to manage your game nodes properly to prevent unwanted behavior and potential memory leaks.
# Assuming your player entity has a gravity value and a velocity vector declared
func _physics_process(delta):
if current_plane == "2D":
apply_gravity(delta)
if is_on_floor() and velocity.y > 0:
velocity.y = 0 # Reset velocity when on the ground to prevent accumulation
# Continue with the rest of your _physics_process logic, such as getting input.
func apply_gravity(delta):
if current_plane == "2D":
velocity.y += gravity * delta # Apply gravity to the y-axis
Finally, when calling move.execute(), refrain from resetting the velocity inside the execute method. Instead, just adjust the velocity according to the player’s inputs and the natural forces (like gravity) acting upon them.
By following these changes, gravity will apply to the player even while moving in any horizontal direction, jumping will only trigger if the player is on the floor, and you will maintain the consistency of the velocity vector across different physics frames. Remember to keep the handle for floor detection (is_on_floor()) and directional influence separate for flexibility and clear conditional checks.