how can I make so it seems like the background has a collision in a 2.5d game in godot? I added the picture as the background now I need to make so the user can move freely up and down on the map and only colide with the edges or walla
my character:
extends CharacterBody2D
class_name Player25D
enum State { IDLE, RUN, JUMP, ATTACK }
var state = State.IDLE
var bullets_amount: int = 30
var attack_animation: String = "Attack1"
var player_base = PlayerBase.new()# Use PlayerBase’s set_health method¨
@export var movement_data : MovementData
@export var stats : Stats
References
@onready var animator : AnimatedSprite2D = AnimatedSprite2D@onreadyvargunsanimator:AnimationPlayer=ShootingAnimationPlayer
@onready var hit_animator : AnimationPlayer = HitAnimationPlayer@onreadyvarhand:NHand
@onready var pistol : Sprite2D = Hand/Pivot/Pistol@onreadyvaHand/Pivot/Pistol/PistolBulletMarker
@onready var attacking: bool = false
@export var camera: Camera2D
Load Scenes
@onready var muzzle_load: PackedScene = preload("res://Scenes/Particles/muzzle.tscn")
@onready var bullet_load: PackedScene = preload("res://Scenes/Props/bullet.tscn")
@onready var death_particle_load: PackedScene = preload("res://Scenes/Particles/player_death_particle.tscn")
var input_vector = Input.get_axis("move_left","move_right")
if input_vector != 0:
apply_acceleration(input_vector, delta)
else:
apply_friction(delta)
if Input.is_action_just_pressed("SwapPlane"):
_on_swapPlane()
if Input.is_action_just_pressed("jump") and is_on_floor():
jump()
if Input.is_action_just_pressed("shoot"):
animator.play("Attacking")
if bullets_amount:
guns_animator.play("Shoot")
move_and_slide()
animate(input_vector)
func process_actions():
if Input.is_action_just_pressed("jump") and is_on_floor():
perform_jump()
if Input.is_action_just_pressed("shoot"):
perform_attack()
func animate(input_vector):
var mouse_position : Vector2 = (get_global_mouse_position() - global_position).normalized()
if mouse_position.x > 0 and animator.flip_h:
animator.flip_h = false
elif mouse_position.x < 0 and not animator.flip_h:
animator.flip_h = true
code
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 state != State.ATTACK:
if is_on_floor():
if input_vector != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
if velocity.y > 0:
animator.play("Jump")
# Check if the current animation is the attack animation
$Hand/AttackArea/CollisionShape2D.disabled = true;
state = State.IDLE
func update_animation_state():
if state == State.ATTACK:
return
code
if is_on_floor():
if velocity.x != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
animator.play("Jump") if velocity.y < 0 else animator.play("Fall")
func _on_hurtbox_area_entered(_area):
if not _area.is_in_group("Bullet"):
hit_animator.play("Hit")
take_damage(1) # If damage is to be variable, extract value from _area
EventManager.frame_freeze.emit()
func spawn_death_particle():
var death_particle = death_particle_load.instantiate()
death_particle.global_position = global_position
get_tree().current_scene.add_child(death_particle)
Override PlayerBase method
func take_damage(damage: int) -> void:
player_base.health -= damage # Use the health property from PlayerBase
if player_base.health <= 0:
die()
else:
AudioManager.play_sound(AudioManager.HURT)
func _on_swapPlane():
PlayerState.set_last_2d_position(global_position);
SceneChanger.change_to_3d(global_position) # Calls the singleton to change to 3D scene
Implement the move method required by PlayerBase, the actual movement
logic is in the _physics_process function above.
func move(input_dir: Vector2) -> void:
# For Player2D, the move function is handled by process_movement_input,
# so no additional logic is needed here.
pass
Implement the attack method required by PlayerBase. This is a placeholder
and the actual logic for starting an attack is in the perform_attack function.
func attack() -> void:
perform_attack()
code
# Adjust the jump method to use jump_strength from PlayerBase
func _on_health_changed(new_health: int) -> void:
player_base.health = new_health # Make sure to update it when health changes
# Handle health change (e.g., update UI)
Assistant
To make the background in your 2.5D game in Godot seem like it has a collision, you need to create collision boundaries for the areas where you don't want your character to be able to go through, like walls or edges. In Godot, you do this with collision shapes that are not visible but define the physical boundaries for objects in the game world.
Here is a step-by-step process to set up collisions for your background:
Scene Setup: Make sure your background is a part of your game scene. It might be a Node2D with a Sprite child where the texture of your background is set.
StaticBody2D: For the walls and edges, where you want your character to collide with the background, you need to add StaticBody2D nodes at those places. These nodes will act as immovable objects that other physics bodies can collide with.
CollisionShape2D: For each StaticBody2D node, add a CollisionShape2D node as its child. In the CollisionShape2D properties, set a shape that matches the area you want to be collidable. It can be a RectangleShape (RectangleShape2D) for straight walls or a PolygonShape (PolygonShape2D) for more complex shapes.
Adjusting Shapes: Position and scale the collision shapes to match the boundaries of your walls and edges in the background. You might need multiple StaticBody2D nodes with different shapes to cover all areas.
Layer and Mask settings: Make sure your StaticBody2D nodes are on a collision layer that your player's CharacterBody2D can detect (i.e., make sure the player's collision mask includes the layer that the static bodies are on).
Testing: Run the game and ensure that the character collides with the walls and edges as expected. Adjust the collision shapes as necessary for better accuracy.
Here's an example code snippet to add a simple rectangular collision wall to the background in Godot:
gdscript
# Background scene
extends Node2D
func _ready():
# Assuming your background is set up
add_wall(Vector2(100, 300), Vector2(400, 20)) # Add a horizontal wall
func add_wall(position, size):
var wall = StaticBody2D.new()
var shape = RectangleShape2D.new()
shape.extents = size * 0.5
var collision = CollisionShape2D.new()
collision.shape = shape
wall.position = position
wall.add_child(collision)
add_child(wall)
User
the player just falls straight down right now? :
extends CharacterBody2D
class_name Player25D
enum State { IDLE, RUN, JUMP, ATTACK }
var state = State.IDLE
var bullets_amount: int = 30
var attack_animation: String = "Attack1"
var player_base = PlayerBase.new()# Use PlayerBase’s set_health method¨
@export var movement_data : MovementData
@export var stats : Stats
References
@onready var animator : AnimatedSprite2D = AnimatedSprite2D@onrShootingAnimationPlayer
@onready var hit_animator : AnimationPlayer = Hand
@onready var pistol : Sprite2D = Hand/Pivot/Pistol/PistolBulletMarker
@onready var attacking: bool = false
@export var camera: Camera2D
Assistant
If your player character just falls straight down and doesn't collide with the floor, make sure you have a floor defined with collision shapes to stop the fall.
Floor Setup: Similar to setting up walls, you need to have a StaticBody2D node at the location of your floor with a CollisionShape2D child that matches the size and shape of the floor.
Player Collision: Ensure your player's CharacterBody2D has a CollisionShape2D or CollisionPolygon2D with a defined shape representing the player's collision area.
Update Floor Collisions: Check your floor StaticBody2D nodes to ensure they have the right collision layers and masks. The player's collision mask needs to include the layer that the floor is on so they can interact.
Adjusting Gravity Code: Your current apply_gravity function appears to continuously add gravity even if the player is on the ground, ensure this is not the case by adjusting the method:
gdscript
func apply_gravity(delta):
if not is_on_floor():
velocity.y += movement_data.gravity * movement_data.gravity_scale * delta
else:
velocity.y = 0
Correct Movement and Slide Parameters: Your move_and_slide call in _physics_process is missing the velocity and floor normal parameters. You need to add the call like this:
gdscript
# Define the up direction for your 2D world. It's usually Vector2.UP, or (0, -1)
var floor_normal = Vector2.UP
func _physics_process(delta):
# Rest of your code...
move_and_slide(velocity, floor_normal)
Fix Player's move_and_slide Call: Since move_and_slide requires velocity to move the character body, ensure that velocity is being tracked as part of the player class, otherwise, you need to create a velocity vector for this purpose.
gdscript
# Add this property to your player class
var velocity = Vector2.ZERO
Debugging Collisions: If things still aren't working, you can debug collisions by turning on visible collision shapes. You can do this by going to "Debug" in the top menu and checking "Visible Collision Shapes" when running your game.
After making sure all collision setups are correct and ensuring the velocity is declared and moved properly with move_and_slide, your player should no longer fall endlessly and should collide with the floor as expected.
User
this is my player:
extends "res://Scripts/Characters/Player/player25D.gd"
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
code
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
this is the prototype,
Background scene
extends Node2D
func _ready():
# Assuming your background is set up
add_wall(Vector2(100, 300), Vector2(400, 20)) # Add a horizontal wall
func add_wall(position, size):
var wall = StaticBody2D.new()
var shape = RectangleShape2D.new()
shape.extents = size * 0.5
var collision = CollisionShape2D.new()
collision.shape = shape
code
wall.position = position
wall.add_child(collision)
add_child(wall)
Assistant
From your player script, it appears that you are moving the player character using move_and_slide without any arguments. You should define a velocity as a member variable for the player class and make sure to provide this velocity as an argument to move_and_slide along with the floor normal.
Here's an updated version of your player script with the necessary changes:
gdscript
extends "res://Scripts/Characters/Player/player25D.gd"
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
# Define a velocity for the player
var velocity = Vector2.ZERO
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
else:
velocity.y = 0 # Reset the y velocity if on the floor
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED * delta)
# Define the up direction for your 2D world. It's usually Vector2.UP, or (0, -1)
var floor_normal = Vector2.UP
# Now you must use velocity as an argument to move_and_slide() function
move_and_slide(velocity, floor_normal)
I changed the move_and_slide function call to use the velocity and floor_normal as arguments, which ensures the character uses the velocity we manage in the script and gives it floor detection () capabilities.
There are a few important aspects to consider when setting up a 2.5D level in Godot. Let's discuss these, and you can check if any of these are missing or misconfigured in your case:
Collision Setup:
Ensure that your StaticBody2D and its child CollisionShape2D have been positioned and sized correctly to cover the areas where you expect collision. The StaticBody2D node should not move, and its CollisionShape2D should define the physical boundaries where the player character should stop.
Player Collision:
Your player needs to have a CollisionShape2D as a child of the CharacterBody2D. Make sure it is sized and positioned to match the player's sprite and desired collision boundary.
Layer and Mask:
In Godot, collision layers and masks define how different bodies and areas interact. The player's collision mask must include the layer where your StaticBody2D is on. Vice versa, the StaticBody2D collision layer should be included in the player's collision mask for collisions to register properly.
Physics Material:
The PhysicsMaterial assigned to your StaticBody2D implies that it's rough (rough = true). This should be fine, but ensure it doesn't have settings that would prevent expected collisions (for instance high bounce or setting it as disabled).
TileMap:
If you are using a TileMap node to place tiles that the player should collide with, each of these tiles needs to have a collision shape defined in the TileSet. Check the TileSet to make sure that the relevant tiles have collision shapes defined.
Scene Organization:
The scene tree should be organized in a way that you have a clear hierarchy for your physics bodies. StaticBody2D nodes that are meant for collision should not be children of any nodes that move or affect transforms in a way that might disrupt collision detection.
Player Physics Code:
Check your player script to ensure that velocity is applied correctly and that move_and_slide is used correctly with the correct method arguments. Ensure is applied only when the player is not on the floor.
User
So right now the background collision counts as floor and the character gets thrown on top of the colision box, want it to be as a floor so you can walk araound on the background map
Assistant
If your character is being thrown on top of the collision box and you want the character to walk around on top of the background map, it seems that your collision setup might not be correctly done for a 2.5D platform. Here's how to set up a floor that the player can walk on:
Floor Collision Shape: Make sure that the CollisionShape2D for the floor is a rectangle (using RectangleShape2D) that covers the entire width and length of the floor area where the player should be able to walk.
Collision Layer and Mask: Double-check that your player's collision mask includes the layer on which the floor's StaticBody2D is set. You can configure this in the Inspector when you click on the player node or floor node under "Collision"->"Layer" and "Mask".
Player Movement: Inspect your player's physics process function to ensure that the gravity is correctly applied and that when is_on_floor() returns true, the gravity is being neutralized or set to zero, so the player stays on the ground. For example:
Floor Normal Parameter in move_and_slide: When using move_and_slide, pass in the floor_normal parameter which is Vector2.UP by default. It tells the method which direction is up and therefore which way is the floor. For a character that walks on a horizontal surface, this should be:
gdscript
move_and_slide(velocity, Vector2.UP)
StaticBody2D Positioning: Your StaticBody2D that represents the floor should be positioned beneath the player character. If your player character is colliding with the StaticBody2D and being pushed above it, perhaps the StaticBody2D is not in the correct position, or the collision shapes are not sized or placed correctly.
Assuming you're creating a platformer map with a visible "floor" that the player character can walk on:
gdscript
User
rewrite this for me to fix that because right now I don't get thrown ontop of the collision box but I cant move around:
extends CharacterBody2D
class_name Player25D
enum State { IDLE, RUN, JUMP, ATTACK }
var state = State.IDLE
var bullets_amount: int = 30
var attack_animation: String = "Attack1"
var player_base = PlayerBase.new()# Use PlayerBase’s set_health method¨
@export var movement_data : MovementData
@export var stats : Stats
References
@onready var animator : AnimatedSprite2D = AnimatedSprite2D@onrShootingAnimationPlayer
@onready var hit_animator : AnimationPlayer = Hand
@onready var pistol : Sprite2D = Hand/Pivot/Pistol/PistolBulletMarker
@onready var attacking: bool = false
@export var camera: Camera2D
Assistant
From the code you provided, it looks like you're not applying the player's velocity anywhere. This is why you can't move even though you're calculating the acceleration and friction. You need to call move_and_slide() with your velocity to ensure the player moves based on the calculated velocity. I've rewritten some parts of your code to include this.
Make sure that velocity is defined in your class as a member variable and initialized properly:
gdscript
var velocity: Vector2 = Vector2.ZERO # Add this line to define velocity
Then rewrite your _physics_process function and related methods to properly handle movement:
gdscript
func _physics_process(delta):
process_input(delta) # Process player input and apply to velocity
apply_gravity(delta) # Apply gravity only when not on the floor
move_and_slide(velocity, Vector2.UP) # Move the player, Vector2.UP is the default floor normal
animate() # Update the player's animation based on current state and velocity
# Your existing code for applying acceleration and applying friction seems okay.
# Just ensure they actually modify the `velocity` variable.
# Here's how the apply_gravity might look
func apply_gravity(delta):
if not is_on_floor():
velocity.y += movement_data.gravity * delta
else:
velocity.y = 0 # Stop falling when on the floor
# Simplify the process_input to handle both movement and jumping
func process_input(delta):
var input_vector = Input.get_axis("move_left", "move_right")
# Movement on X-axis
if input_vector != 0:
velocity.x = move_toward(velocity.x, movement_data.max_speed * input_vector, movement_data.acceleration * delta)
else:
velocity.x = move_toward(velocity.x, 0, movement_data.friction * delta)
# Jumping
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = -movement_data.jump_strength
# Shooting
if Input.is_action_just_pressed("shoot"):
perform_attack()
# Remove the two below functions (process_gravity and process_movement_input)
# as they are now combined into the process_input function
User
now the character ends up flying to the top again
Assistant
If your character is being thrown upwards when you expect them to walk on the floor, it's usually because of incorrectly applied forces or a misconfigured collision setup.
Here's what you should check and fix:
1. Gravity and Jump
Ensure that gravity is only applied when the player is not grounded, and ensure the jump force is negative (assuming a coordinate system where up is negative on the y-axis).
gdscript
func apply_gravity(delta):
if not is_on_floor():
velocity.y += movement_data.gravity * movement_data.gravity_scale * delta
When jumping, also make sure the force is correctly directed:
gdscript
func perform_jump():
velocity.y = -movement_data.jump_strength # This should make the player go upwards, not down
2. move_and_slide Correct Usage
Make sure you use move_and_slide() correctly with the velocity and tell Godot which direction is up using Vector2.UP:
Ensure your perform_jump() and any other manipulation of velocity occurs on the correct axis. Godot's coordinate system has (0, 0) at the top left, with y values increasing downwards:
gdscript
func perform_jump():
velocity.y = -movement_data.jump_strength # As we want to jump up
4. Collisions and Layers
Make sure the collision shapes for both your player and your static bodies (like the floor) have the correct layers and masks set. The player should have a layer set that the floor includes in its mask, and vice versa.
5. Debug the Collisions
You can debug collisions by turning on "Visible Collision Shapes" from the "Debug" menu at the top of the Godot editor. This will show you the collision shapes when you run the scene, which can be very helpful in understanding what's happening.
6. Script Execution Order
Ensure there are no scripts elsewhere that might be inadvertently affecting the player's position or velocity.
Make sure to adjust the code to fit within the structure of your own scene and to position the walls correctly. The add_wall function should take a position where the center of the wall will be and a size that defines the width and height of the wall. The actual creation of the walls should ideally be done in a level design phase and not hardcoded, but the above code serves as a simple example.
var input_vector = Input.get_axis("move_left","move_right")
if input_vector != 0:
apply_acceleration(input_vector, delta)
else:
apply_friction(delta)
if Input.is_action_just_pressed("SwapPlane"):
_on_swapPlane()
if Input.is_action_just_pressed("jump") and is_on_floor():
jump()
if Input.is_action_just_pressed("shoot"):
animator.play("Attacking")
if bullets_amount:
guns_animator.play("Shoot")
move_and_slide()
animate(input_vector)
func process_actions():
if Input.is_action_just_pressed("jump") and is_on_floor():
perform_jump()
if Input.is_action_just_pressed("shoot"):
perform_attack()
func animate(input_vector):
var mouse_position : Vector2 = (get_global_mouse_position() - global_position).normalized()
if mouse_position.x > 0 and animator.flip_h:
animator.flip_h = false
elif mouse_position.x < 0 and not animator.flip_h:
animator.flip_h = true
code
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 state != State.ATTACK:
if is_on_floor():
if input_vector != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
if velocity.y > 0:
animator.play("Jump")
# Check if the current animation is the attack animation
$Hand/AttackArea/CollisionShape2D.disabled = true;
state = State.IDLE
func update_animation_state():
if state == State.ATTACK:
return
code
if is_on_floor():
if velocity.x != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
animator.play("Jump") if velocity.y < 0 else animator.play("Fall")
func _on_hurtbox_area_entered(_area):
if not _area.is_in_group("Bullet"):
hit_animator.play("Hit")
take_damage(1) # If damage is to be variable, extract value from _area
EventManager.frame_freeze.emit()
func spawn_death_particle():
var death_particle = death_particle_load.instantiate()
death_particle.global_position = global_position
get_tree().current_scene.add_child(death_particle)
Override PlayerBase method
func take_damage(damage: int) -> void:
player_base.health -= damage # Use the health property from PlayerBase
if player_base.health <= 0:
die()
else:
AudioManager.play_sound(AudioManager.HURT)
func _on_swapPlane():
PlayerState.set_last_2d_position(global_position);
SceneChanger.change_to_3d(global_position) # Calls the singleton to change to 3D scene
Implement the move method required by PlayerBase, the actual movement
logic is in the _physics_process function above.
func move(input_dir: Vector2) -> void:
# For Player2D, the move function is handled by process_movement_input,
# so no additional logic is needed here.
pass
Implement the attack method required by PlayerBase. This is a placeholder
and the actual logic for starting an attack is in the perform_attack function.
func attack() -> void:
perform_attack()
code
# Adjust the jump method to use jump_strength from PlayerBase
func _on_health_changed(new_health: int) -> void:
player_base.health = new_health # Make sure to update it when health changes
# Handle health change (e.g., update UI)
is_on_floor
Additionally, I reset the velocity.y to 0 when the player is on the floor to prevent them from accelerating downwards when in contact with a floor.
Lastly, in the apply_friction part, I have multiplied SPEED by delta to ensure the move_toward function provides smooth results since this method usually runs each frame and the distance should be time-sensitive.
Please make sure to add proper collision shapes (using CollisionShape2D or CollisionPolygon2D depending on the need) to the player character and the walls for the collision to work properly. Also, ensure that there is a floor set up the same way as the walls which includes a StaticBody2D with a CollisionShape2D child node. The correct layer and mask settings must also be configured for the collision to register.
With these changes, your player character should be able to jump, move left and right using input, and not fall endlessly, colliding with floors and walls as expected.
In your existing code, the Player node has a movement_data resource with zero values for all properties. This means your player's speed, acceleration, and other movement properties are set to zero, which might be one reason why you wouldn't see any movement:
gdscript
movement_data = SubResource("Resource_firy0")
Ensure that you've set proper values for the MovementData resource.
If everything seems correct and you're still experiencing issues, try enabling "Visible Collision Shapes" in the Debug menu of the editor to visually inspect collision shapes during runtime. This will help determine if collision shapes are placed correctly in relation to the player and the world.
Last but not least, carefully check the MovementData and Stats resources used by the player, and make sure all expected values are non-zero and make sense for your game's physics and gameplay.
Without the ability to inspect the full setup interactively, including the script logic, it's challenging to identify the exact issue. If possible, review the settings mentioned above, and consider performing isolated tests with simple scenes to ensure collision detection is working as expected before adding complexity.
# Example floor setup:
func create_floor(x, y, width, height):
var floor = StaticBody2D.new()
var shape = RectangleShape2D.new()
shape.extents = Vector2(width / 2, height / 2) # Half of the width and height
var collision = CollisionShape2D.new()
collision.shape = shape
floor.add_child(collision)
floor.position = Vector2(x, y)
add_child(floor)
In this script, the create_floor function is an example of how you might programmatically create a floor; x and y are the center position of the floor, width and height are the dimensions of the floor, and the function adds a StaticBody2D with a collision shape to your level. You would need to call this function with the right arguments to match your game's measurements and positions.
Finally, make sure to use the Godot editor's 2D view to align your floor collision correctly with the sprite that represents your game's floor. Visually checking will ensure that the StaticBody2D and CollisionShape2D are correctly lining up with where you want the player to make contact with the floor.
var input_vector = Input.get_axis("move_left","move_right")
if input_vector != 0:
apply_acceleration(input_vector, delta)
else:
apply_friction(delta)
if Input.is_action_just_pressed("SwapPlane"):
_on_swapPlane()
if Input.is_action_just_pressed("shoot"):
animator.play("Attacking")
if bullets_amount:
guns_animator.play("Shoot")
animate(input_vector)
func process_actions():
if Input.is_action_just_pressed("jump") and is_on_floor():
perform_jump()
if Input.is_action_just_pressed("shoot"):
perform_attack()
func animate(input_vector):
var mouse_position : Vector2 = (get_global_mouse_position() - global_position).normalized()
if mouse_position.x > 0 and animator.flip_h:
animator.flip_h = false
elif mouse_position.x < 0 and not animator.flip_h:
animator.flip_h = true
code
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 state != State.ATTACK:
if is_on_floor():
if input_vector != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
if velocity.y > 0:
animator.play("Jump")
# Check if the current animation is the attack animation
$Hand/AttackArea/CollisionShape2D.disabled = true;
state = State.IDLE
func update_animation_state():
if state == State.ATTACK:
return
code
if is_on_floor():
if velocity.x != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
animator.play("Jump") if velocity.y < 0 else animator.play("Fall")
func _on_hurtbox_area_entered(_area):
if not _area.is_in_group("Bullet"):
hit_animator.play("Hit")
take_damage(1) # If damage is to be variable, extract value from _area
EventManager.frame_freeze.emit()
func spawn_death_particle():
var death_particle = death_particle_load.instantiate()
death_particle.global_position = global_position
get_tree().current_scene.add_child(death_particle)
Override PlayerBase method
func take_damage(damage: int) -> void:
player_base.health -= damage # Use the health property from PlayerBase
if player_base.health <= 0:
die()
else:
AudioManager.play_sound(AudioManager.HURT)
func _on_swapPlane():
PlayerState.set_last_2d_position(global_position);
SceneChanger.change_to_2d(global_position) # Calls the singleton to change to 3D scene
Implement the move method required by PlayerBase, the actual movement
logic is in the _physics_process function above.
func move(input_dir: Vector2) -> void:
# For Player2D, the move function is handled by process_movement_input,
# so no additional logic is needed here.
pass
Implement the attack method required by PlayerBase. This is a placeholder
and the actual logic for starting an attack is in the perform_attack function.
func attack() -> void:
perform_attack()
code
# Adjust the jump method to use jump_strength from PlayerBase
func _on_health_changed(new_health: int) -> void:
player_base.health = new_health # Make sure to update it when health changes
# Handle health change (e.g., update UI)
Make sure movement_data is configured with non-zero values in your Godot editor or in the MovementData script you're referencing.
Lastly, your animate function should take into account the direction of the character (for example, left or right), and play the appropriate animation based on movement and state. Here's a simplified version that only checks for idling or running:
gdscript
func animate():
if is_on_floor():
if velocity.x != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
animator.play("Jump") if velocity.y < 0 else animator.play("Fall")
These modifications should allow your player to walk around on the background map, given that the movement_data resource has sensible values for speed, acceleration, and gravity. Remember to check layers and masks to ensure collisions are registered correctly.
Here is a sample script incorporating some of the above checks and adjustments:
gdscript
var velocity: Vector2 = Vector2()
func _ready():
# ... your initialization code ...
func _physics_process(delta):
process_input(delta)
apply_gravity(delta)
velocity = move_and_slide(velocity, Vector2.UP)
animate()
func apply_gravity(delta):
if not is_on_floor():
velocity.y += movement_data.gravity * movement_data.gravity_scale * delta
else:
velocity.y = 0
func process_input(delta):
var input_vector = Input.get_axis("move_left", "move_right")
if input_vector != 0:
velocity.x = move_toward(velocity.x, movement_data.max_speed * input_vector, movement_data.acceleration * delta)
else:
velocity.x = move_toward(velocity.x, 0, movement_data.friction * delta)
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = -movement_data.jump_strength
# Your shooting code ...
func animate():
if is_on_floor():
if velocity.x != 0:
animator.play("Run")
else:
animator.play("Idle")
else:
if velocity.y < 0:
animator.play("Jump")
else:
animator.play("Fall")
# ... rest of your script ...
Make sure your MovementData is correctly set up with positive values for gravity and max_speed, and a negative value for jump_strength.
Finally, recheck your scene setup and ensure that all physical bodies are configured correctly, including collision shapes, layers, and masks. Once all these settings are verified, your character should be able to walk around without flying to the top.