I want to move to be modular but I also want to apply gravity to the entitys that has…
- User
I want to move to be modular but I also want to apply gravity to the entitys that has move loaded when they are in a 2dplane:
extends Node2D
Called when the node enters the scene tree for the first time.
func execute(s, dir = []): s.velocity = Vector2(0,0) if dir.has("up") && GameManager.current_plane != "2D": s.velocity.y -= 1 if dir.has("down") && GameManager.current_plane != "2D": s.velocity.y += 1 if dir.has("left"): s.velocity.x -= 1 if dir.has("right"): s.velocity.x += 1
if dir.has("jump") && GameManager.current_plane == "2D": s.velocity.y -= 1 if dir.size(): s.velocity = s.velocity * s.current_speed s.velocity.normalized() s.move_and_slide()entity: extends CharacterBody2D class_name Entity
#var death_scene = var death_config = {} var direction : Vector2 = Vector2()
var max_health = 40 var current_health : int = 40 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 has_gravity = true
var gravity: float = 98.0 # Adjust the gravity force as needed
func get_State(): return { "direction": direction, "max_health": max_health, "current_health": current_health, "health_regen": health_regen, "armor": armor, "max_mana": max_mana, "current_mana": current_mana, "mana_regen": mana_regen, "max_speed": max_speed, "current_speed": current_speed, "acceleration": acceleration, "agility": agility, "global_cooldown": global_cooldown, "is_busy": is_busy, "last_ability": last_ability, "is_player": is_player } func _ready(): add_to_group("entity")
func get_enemies(): var enemy_group = get_enemy_group() var enemies = get_tree().get_nodes_in_group(enemy_group) return enemies
func get_enemy_group(): var enemy_group = "friend" if is_player: enemy_group = "foe" return enemy_group
func find_nearest_enemy(): return get_enemies()[0]
func get_aim_position(): if is_player: return get_global_mouse_position() else: return find_nearest_enemy().global_position
func regen_health(): if (current_health < max_health): if((health_regen + current_health) > max_health): current_health = max_health else: current_health += health_regen if is_player:EventManager.regen_health_ui.emit(current_health)
func regen_mana(): if (current_mana < max_health): if((mana_regen + current_mana) > max_mana): current_mana = max_mana else: current_mana += mana_regen
func modify_mana(amount): var new_mana = current_mana + amount if(new_mana < 0): current_mana = 0 if(new_mana > max_mana): current_mana = max_mana else: current_mana += amount
func can_cast_ability(mana_cost): if(current_mana - mana_cost) >= 0: modify_mana(-mana_cost) return true else: print("not enough mana!") return false
func apply_damage(amount): if is_player: EventManager.frame_freeze.emit() EventManager.update_health_ui.emit(amount) if(armor > 0): amount = amount *((100-armor)*0.01) if(current_health > amount): current_health -= amount else: current_health = 0 if(!is_player): #var loot = death_scene.instantiate() #loot.position = self.global_position #loot.config = death_config #get_nod("/root").add_child(loot) self.queue_free() else: die()
func _physics_process(delta): last_ability += 1 if has_gravity: apply_gravity(delta) if ((GameManager.count % 60) == 0): regen_health() regen_mana()
func load_ability(ability_name): var scene = load("res://Scenes/abilities/" + ability_name + "/" + ability_name + ".tscn") var sceneNode = scene.instantiate() add_child(sceneNode) return sceneNode
func die(): AudioManager.play_sound(AudioManager.DEATH) EventManager.player_died.emit() queue_free()
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
# 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 - Assistant
It looks like you're trying to add modular movement and gravity to entities in your 2D game using Godot Engine. To make your code modular and enable gravity on the entities when they are moving on a 2D plane, you'll need to refactor your code a bit.
Here's a suggested refactor to accommodate what you're trying to achieve, keeping in mind that some context is missing, such as the GameManager and EventManager that are referred to in the script. I'm assuming GameManager.current_plane is a string that lets you know whether the entity should be affected by gravity or not, and EventManager is used for UI updates and audio.
First, let's refactor the Entity script so that it has gravity and movement applied properly in a modular fashion:
extends CharacterBody2D class_name Entity # ... [Other properties as needed] ... var velocity = Vector2() var gravity = 98.0 # The gravity constant var on_ground = false # A flag to check if the entity is on ground # ... [Other functions as needed] ... func _physics_process(delta): # Handle gravity if in a 2D plane and the entity has gravity enabled if GameManager.current_plane == "2D" and has_gravity: apply_gravity(delta) # Here you would include your logic to process movement inputs process_movement_input(delta) # Regeneration if GameManager.count % 60 == 0: regen_health() regen_mana() func process_movement_input(delta): # Assuming you gather some input to determine the direction # For example, if you have a function get_input_direction() that returns a Vector2: var input_dir = get_input_direction() # Normalize the direction and multiply by the current speed velocity.x = input_dir.x * current_speed # If entity is on the ground and the input includes a jump, apply an initial jump velocity if input_dir.y == -1 and on_ground: # Assuming -1 on Y is up, adjust as needed velocity.y = -initial_jump_force # Move and slide velocity = move_and_slide(velocity, Vector2.UP) # Check if on ground after moving on_ground = is_on_floor() func apply_gravity(delta): # If not on ground, apply gravity if not on_ground: velocity.y += gravity * delta else: # Reset the y velocity to zero if on the ground velocity.y = 0 # ... [Other methods as needed] ...The scripts above take care of applying gravity only if the conditons are right: when the entity is on a 2D plane and gravity is enabled. Also, the method
process_movement_input(delta)is a placeholder and you'll need to flesh it out based on how your game handles input.The modular
apply_gravity(delta)function will only apply gravity to the entity's velocity if it's not on the ground. Theon_groundflag is set after eachmove_and_slide()call.Please note:
- If executing this code within Godot Engine, ensure that the nodes correspond to the appropriate types (i.e.,
CharacterBody2Dshould match the class you're extending here). - The
initial_jump_forceshould be defined in your properties if you're implementing jumping. get_input_direction()is a placeholder function you would replace with whatever input-gathering logic your game uses to determine movement direction.
As for the
executefunction at the beginning, I suggest integrating that logic into the entity's_physics_process(delta)function while keeping the movement code modular, as shown. Theexecutefunction as written doesn't seem to be directly usable with the entity code. You should merge the functionality properly, maybe separating movement calculation from input processing. - If executing this code within Godot Engine, ensure that the nodes correspond to the appropriate types (i.e.,
- User
but currently I apply movement on the type that is inhereting:
extends Entity class_name Player25D enum State { IDLE, RUN, JUMP, ATTACK } var attack_animation: String = "Attack1" @onready var animator : AnimatedSprite2D = 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 swap_plane = false var state = State.IDLE var gold : int = 0 var crystals : int = 0
func _ready(): super._ready() add_to_group("player") add_to_group("friend") EventManager.set_health_ui.emit(max_health) pass
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
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 _physics_process(delta): _read_input() super._physics_process(delta)
func _on_swapPlane(): swap_plane = true PlayerState.set_last_2d_position(global_position) if GameManager.current_plane == "2D": GameManager.current_plane = "25D" SceneChanger.change_to_25d(global_position) # Calls the function to change to 2.5D scene else: GameManager.current_plane = "2D" SceneChanger.change_to_2d(global_position) # Calls the function to change to 2D scene swap_plane = false
- Assistant
To integrate the
movemodule (which appears to be a loaded ability) into the modular setup described earlier, you'll need to adapt both theEntityclass and thePlayer25Dclass to work together in a cohesive way. The goal is to use_read_input()to collect player input, determine actions, and apply movement in a consistent way according to whether or not the player is in the 2D or 2.5D plane.Here's an updated version of the
Player25Dclass that includes handling movement input, which could be adapted to use yourmovemodule. Themovemodule will need to take into account the_physics_process(delta)gravity and movement logic that we previously defined in theEntityclass.extends Entity class_name Player25D # ... [Other properties and _ready function as needed] ... func _read_input(): var direction = Vector2.ZERO state = State.IDLE if Input.is_action_pressed("move_up"): direction.y -= 1 if Input.is_action_pressed("move_down"): direction.y += 1 if Input.is_action_pressed("move_right"): direction.x += 1 if Input.is_action_pressed("move_left"): direction.x -= 1 if Input.is_action_just_pressed("jump"): # You can add jump specific logic here # Normalize the direction if movement is diagonal if direction.length() > 1: direction = direction.normalized() if direction != Vector2.ZERO: state = State.RUN # Replace the execute with direct movement control or integrate your movement ability accordingly Move(self, direction) # ... func _physics_process(delta): _read_input() process_movement_input(delta) # This might be inherited from Entity or custom for Player25D super._physics_process(delta) # Make sure to call the parent's _physics_process # Additional state checking and animation control if state == State.RUN: animator.play("Run") else: animator.play("Idle") # ... [Rest of the Player25D class functions] ...With this structure, you want to ensure that the
executefunction of yourmovemodule can be seamlessly integrated into thePlayer25D’s custom_physics_processfunction. Themovemodule (which is a loaded ability) needs to operate by applying the direction calculated based on keyboard input.However, it's not clear from the code you've provided what exactly the
movemodule'sexecutefunction does and how it interacts with the entity's velocity. You might need to redesign themovemodule to use thevelocityvariable directly or modify its interface to fit better with your movement needs when the player switches planes or operates on a different movement logic in 2D and 2.5D modes.Remember that when working with Godot's
move_and_slidefunction, it expects the velocity to be in pixels per second, so you should adjust the velocities accordingly.In essence, you're trying to keep the handling of input (
_read_input) separate from the physics processing (_physics_process) while still allowing for modular insertion of abilities or behaviors (such as yourmovemodule). This keeps each part of your code responsible for one thing, which is a good design principle to follow for maintainability and clarity. - User
how to make the jump smoother so it doesn't teleport the -= 50:
func jump(s): # Apply gravity to the player’s velocity if s.is_on_floor(): s.velocity.y -= 50 s.velocity.normalized() s.move_and_slide()
func apply_gravity(s): # Apply gravity to the player’s velocity if GameManager.current_plane == "2D": # Apply gravity to the player’s velocity if !s.is_on_floor(): s.velocity.y += gravity
# Move the player and process collisions if s is CharacterBody2D: # Assuming you have a floor_normal set up correctly and a max_slides value # You can reset y velocity if on the floor if s.is_on_floor(): s.velocity.y = 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 - Assistant
The abrupt change in velocity that you're experiencing when the
jumpfunction is called is due to the immediate reduction in theycomponent of velocity by50. This can give the appearance of "teleporting" as the movement is not gradual but an instantaneous change.To make the jump smoother and more natural, you should apply an initial force to the
velocity.yand then let gravity naturally bring the character back down. Here's how you can update thejumpfunction to do this:func jump(s): # Only allow jumping if the entity is on the floor if s.is_on_floor(): # Apply an initial jump impulse s.velocity.y -= s.jump_impulse # `s.jump_impulse` should be a property representing the initial force to apply when jumping # Note that we don't normalize here, as we specifically want to apply the force just to y. s.move_and_slide(s.velocity, Vector2.UP)Make sure to add a property to the
Entityforjump_impulseso you can tweak the jump strength as needed. For example:var jump_impulse = 800.0 # Adjust this number to get the desired jump strengthAlso, update the
apply_gravityfunction to handle gravity correctly:func apply_gravity(s, delta): # Apply gravity to the entity’s velocity if GameManager.current_plane == "2D": if not s.is_on_floor(): s.velocity.y += s.gravity * delta else: # If the character is on the floor, reset the y velocity to prevent it from accumulating s.velocity.y = 0And here's how you could incorporate the
jumpandapply_gravitymethods into your entity's physics processing:func _physics_process(delta): # Apply gravity apply_gravity(self, delta) # Handle jumping - You will trigger this based on some input like: # if Input.is_action_just_pressed("ui_jump"): # jump(self) # And you should remove the direct call to `move_and_slide` within the `jump` function # Apply horizontal movement # Finally, apply the final velocity using move_and_slide velocity = move_and_slide(velocity, Vector2.UP)Make sure that
jumpis only executed when the jump action button is pressed, not every frame. And the function_physics_processmust be called every frame to keep applying gravity and to allow movement and collision resolution.Don't forget to adjust the
jump_impulseandgravityvariables to fine-tune the jumping behavior to feel right for your game. The values you use for these will depend on your game's specific needs and can vary based on your game's scale, physics settings, and desired player experience. Remember that a higherjump_impulsevalue means a stronger jump, and thegravityconstant should be set to a value that appropriately simulates the acceleration due to gravity in your game world. - User
do it without delta
- Assistant
If you want to implement jumping without using the
deltaparameter, which represents the frame's time since the previous frame and is typically used to make the game frame rate independent, you can still do it. However, it's important to note that not usingdeltawill make the motion frame rate dependent, which means the game might run differently on devices with different frame rates.Here's how you can adjust your jump and gravity functions to work without relying on
delta:const GRAVITY_ACCELERATION = 10.0 # Gravity acceleration per frame const JUMP_IMPULSE = -250.0 # Initial jump velocity func jump(s): # Only allow jumping if the entity is on the floor if s.is_on_floor(): # Apply an initial jump impulse s.velocity.y = JUMP_IMPULSE # No need to normalize when dealing exclusively with y-axis for jumping func apply_gravity(s): # Only apply gravity if the entity is not on the floor if not s.is_on_floor(): # Increment velocity by gravity acceleration s.velocity.y += GRAVITY_ACCELERATION func _physics_process(_delta): # Apply gravity independent of delta apply_gravity(self) # Apply any other motion that your character may need here (e.g., horizontal movement) # Finally, move the character applying the velocity modified by gravity and jump velocity = move_and_slide(velocity, Vector2.UP) # Ensure that the velocity.y doesn't accumulate beyond a maximum fall speed velocity.y = min(velocity.y, max_fall_speed) # where "max_fall_speed" is a defined limit to prevent falling too fastIn the code above:
- You have a constant
GRAVITY_ACCELERATIONthat represents how much vertical speed is added to the character each frame while they're airborne (not on the floor). - You apply a constant
JUMP_IMPULSEwhen the character jumps. This is a negative value to propel the character upwards. - The
_physics_process()function omits the use ofdeltaaltogether and applies gravity and jump velocity directly.
This method will not compensate for varying frame rates, so the actual game operation might vary across different machines. If a machine runs the game at a higher frame rate, the gravity will be applied more times per second and the character will fall faster, and similarly, jumping will feel shorter at higher frame rates.
For smoother and more consistent physics that performs equally well across different device speeds, using
deltais highly advised. If you are developing a game where the frame rate is locked or performing on controlled hardware, then frame-based physics might be acceptable. Otherwise, it is generally best practice to usedeltato ensure consistent gameplay. - You have a constant