Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

help me on how I can apply gravity to this but only if it's on a map with tag 2D:…

  1. User

    help me on how I can apply gravity to this but only if it's on a map with tag 2D:

    extends Entity class_name Player25D enum State { IDLE, RUN, JUMP, ATTACK } var attack_animation: String = "Attack1" @onready var animator : AnimatedSprite2D = AnimatedSprite2D@onreadyvarhand:Node2D=AnimatedSprite2D @onready var hand : Node2D = 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 = Hand/Pivot/Pistol/PistolBulletMarker@onreadyvarsword:AnimationPlayer=Hand/Pivot/Pistol/PistolBulletMarker @onready var sword : AnimationPlayer = ShootingAnimationPlayer var state = State.IDLE var gold : int = 0 var crystals : int = 0 var current_plane = "2D"

    func _ready(): super._ready() add_to_group("player") add_to_group("friend") 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): super._physics_process(delta) _read_input()

    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

  2. Assistant

    To apply gravity specifically when the map has a tag "2D", you'll first want to ensure you have a system in place to detect if the current map has this tag. Once you have that, you'll need to create a gravity variable and apply it to the player's motion when in the 2D map. Below is an example of how you could implement such a system within Godot Engine's scripting environment, extending from your existing Player25D class.

    Assuming that you have a way to identify the map's tag, we will apply gravity using a Vector2 to represent the player's velocity and a gravity constant to affect the vertical movement. You'll also need to handle collisions to stop falling when the player touches the ground. If you are using a KinematicBody2D for your Player25D, you can use the move_and_slide() function to achieve this.

    Here's how to implement gravity into your Player25D class:

    extends Entity
    class_name Player25D
    
    # ... [rest of your existing code] ...
    
    # Define gravity and velocity
    var gravity: float = 2000.0 # Adjust the gravity force as needed
    var velocity: Vector2 = Vector2()
    
    # ... [rest of your existing code] ...
    
    func _physics_process(delta):
        super._physics_process(delta)
        _read_input()
        
        # Apply gravity only if we are on a map with tag "2D"
        if current_plane == "2D":
            velocity.y += gravity * delta
        else:
            velocity.y = 0 # No gravity applied in 2.5D / 3D mode
        
        # Move and slide the player. Assuming the player is a KinematicBody2D
        # You'll need to adjust the floor_normal depending on your game (Vector2.UP is y=-1 for downward gravity)
        velocity = move_and_slide(velocity, Vector2.UP)
        
        # Check for the collision with the ground; if so, set the y velocity to 0
        if is_on_floor():
            velocity.y = 0
    
    # ... [rest of your existing code] ...
    

    In this example, we're assuming you're using a KinematicBody2D as your Entity base class. Make sure that:

    • You have move_and_slide defined in your Entity class.
    • Your Entity class is capable of identifying when it is on the floor with is_on_floor() method.
    • The velocity variable is properly integrated into your movement mechanics.

    Please adjust the gravity value to match the desired strength for your game. You will also need to ensure that you handle jumping separately, as the above script will always apply gravity, and you would likely need to counteract it with an upward impulse when the player jumps.

    Lastly, this example assumes that current_plane is properly set to "2D" when the player is in the relevant environment. Adjust the script as needed based on your exact implementation and class structure.

  3. User

    I'm using a character2d in entity

  4. Assistant

    Given that you're using a Character2D in your Entity, integrating gravity for a 2D map involves modifying the velocity in the _physics_process function, similar to what I described before. However, the exact implementation may depend on how the Character2D class defines motion.

    Since you're checking for the current_plane field to determine the plane you're operating, you'll want to conditionally apply gravity within _physics_process based on that. Here's an adjusted example tailored to your Character2D usage:

    extends Entity
    class_name Player25D
    
    # ... [rest of your existing code] ...
    
    # Define gravity and velocity
    var gravity: float = 2000.0 # Adjust the gravity force as needed
    var velocity: Vector2 = Vector2()
    
    # ... [rest of your existing code] ...
    
    func _physics_process(delta):
        super._physics_process(delta)
        _read_input()
        
        # Apply gravity only if we are on a map with tag "2D"
        if current_plane == "2D":
            velocity.y += gravity * delta
        else:
            velocity.y = 0 # No gravity applied in 2.5D / 3D mode
        
        # Handle horizontal movement (left/right)
        # You'll need to integrate this part with your current movement logic
        # if Input.is_action_pressed("move_right"):
        #     velocity.x = your_move_speed
        # elif Input.is_action_pressed("move_left"):
        #     velocity.x = -your_move_speed
        # else:
        #     velocity.x = 0
        
        # Move the player
        # Replace 'move' with however your Character2D expects to be moved, like 'move_and_collide' or a custom method
        move(velocity * delta)
        
        # After moving, check for collisions and reset velocity if needed.
        # You might need a more complex collision handling system depending on your game's requirements.
        if is_on_floor():
            velocity.y = 0
        # ... also add other collision handling ...
    
    # ... [rest of your existing code] ...
    

    Please integrate it with your existing movement system or adjust it accordingly based on how you have implemented movement and collision detection in your Entity class. If you're relying on Godot's move_and_slide() or move_and_collide() for a KinematicBody2D, substitute the move() call with the appropriate method.

    Note: You may not have the is_on_floor() method by default unless your Entity class, which Player25D extends from, has this logic implemented. If Entity doesn't have such methods, you will need to implement collision detection logic for your Character2D. You could use the get_slide_collision() method after movement to determine if there were any floor collisions.

  5. User

    extends Entity class_name Player25D enum State { IDLE, RUN, JUMP, ATTACK } var attack_animation: String = "Attack1" @onready var animator : AnimatedSprite2D = AnimatedSprite2D@onreadyvarhand:Node2D=AnimatedSprite2D @onready var hand : Node2D = 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 = Hand/Pivot/Pistol/PistolBulletMarker@onreadyvarsword:AnimationPlayer=Hand/Pivot/Pistol/PistolBulletMarker @onready var sword : AnimationPlayer = ShootingAnimationPlayer var gravity: float = 2000.0 # Adjust the gravity force as needed var state = State.IDLE var gold : int = 0 var crystals : int = 0 var current_plane = "2D"

    func _ready(): super._ready() add_to_group("player") add_to_group("friend") 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): super._physics_process(delta) _read_input() if current_plane == "2D": velocity.y += gravity * delta else: velocity.y = 0 # No gravity applied in 2.5D / 3D mode

    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

  6. Assistant

    Based on the script you've provided, it seems you have already started the process of controlling gravity but have yet to implement the actual movement and collision detection that responds to the gravity variable.

    Here are some steps and modifications to apply gravity to your player within the 2D map:

    1. Define a velocity variable that will be affected by gravity.
    2. Add collision detection to stop the player from falling through the ground.
    3. Apply the gravity within _physics_process when on a 2D map.
    4. Use a method like move_and_slide if you are using a KinematicBody2D for movement and collision detection.

    I will assume you're using KinematicBody2D to represent your player's physics and collisions.

    Here's your modified script with these changes:

    extends Entity
    class_name Player25D
    
    # ... [existing variables]
    
    # Adding a velocity variable
    var velocity: Vector2 = Vector2.ZERO
    
    # ... [existing functions]
    
    func _physics_process(delta):
    	super._physics_process(delta)
    	_read_input()
    	
    	# Apply gravity when on a 2D map
    	if current_plane == "2D":
    		# Apply gravity to the player's velocity
    		velocity.y += gravity * delta
    		
    		# Move the player and process collisions
    		if self is KinematicBody2D:
    			# Assuming you have a floor_normal set up correctly and a max_slides value
    			velocity = move_and_slide(velocity, Vector2.UP, true, 4, deg2rad(45))
    			# You can reset y velocity if on the floor
    			if is_on_floor():
    				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
    	else:
    		# If not in a 2D map, don't apply gravity (reset velocity.y)
    		velocity.y = 0
    	
    	# ... (rest of your _physics_process function)
    
    # ... [existing functions]
    

    Remember:

    • The is_on_floor() function works with KinematicBody2D. If your Entity does not inherit this class, you'll need alternative collision handling.
    • You must adjust parameters like floor_normal, stop_on_slope, max_slides, and floor_max_angle according to your own game's physics setup.
    • If your Entity is not a KinematicBody2D nor knows about move_and_slide, you'll need to implement your physics movement system respecting the gravity and collisions.

    Make sure to replace the placeholder code self is KinematicBody2D: and the pass statement with the correct implementation if it's not the correct class. This is just a way to demonstrate where your collision and movement logic might go.

    Lastly, you should implement jumping logic as well, especially modifying velocity.y with a negative value whenever a jump occurs (i.e., if Input.is_action_just_pressed("jump"):) to oppose the force of gravity.

  7. User

    add friction so it doesnt glide and also if you move while you in air you kinda just glide

  8. Assistant

    To add friction and prevent gliding, as well as to control air movement better, you will need to apply some form of horizontal deceleration. In a physics-based movement system, this is commonly achieved using some damping or friction values that reduce the player's horizontal velocity over time.

    In Godot, move_and_slide has a built-in friction parameter that you can utilize. Additionally, you can manually adjust the velocity vector based on whether the player is grounded or in the air.

    Here's a modification to your _physics_process function to include friction and air control:

    extends Entity
    class_name Player25D
    
    # ... [existing variables]
    
    # Adding friction and air control variables
    var friction: float = 500.0 # Amount of friction applied when on the ground
    var air_friction: float = 100.0 # Amount of friction applied in the air
    var air_control: float = 0.2 # Determines how much control the player has in the air (0-1)
    
    # ... [existing functions]
    
    func _physics_process(delta):
    	super._physics_process(delta)
    	_read_input()
    	
    	# Apply gravity when on a 2D map
    	if current_plane == "2D":
    		velocity.y += gravity * delta
    		
    		# Apply horizontal friction if on the ground, less control if in the air
    		if is_on_floor():
    			velocity.x = lerp(velocity.x, 0, friction * delta)
    		else:
    			velocity.x = lerp(velocity.x, 0, air_friction * delta)
    		
    		# If the player is moving in the air, reduce the applied movement to simulate less control
    		if state == State.RUN and !is_on_floor():
    			velocity.x *= air_control
    			
    		if self is KinematicBody2D:
    			velocity = move_and_slide(velocity, Vector2.UP, true, 4, deg2rad(45))
    			if is_on_floor():
    				velocity.y = 0
    		# Handle other Entity cases as required
    	else:
    		velocity.y = 0
    		velocity.x = lerp(velocity.x, 0, friction * delta) # Still apply friction
    	
    	# ... (rest of your _physics_process function)
    
    # ... [existing functions]
    

    In the snippet above:

    • lerp is used to interpolate between the current velocity and the desired target velocity (which is 0 when applying friction).
    • friction is the factor controlling how quickly the character stops when grounded.
    • air_friction is a usually smaller friction value applied when the character is airborne to simulate less deceleration.
    • air_control reduces the effectiveness of player input when in the air, making air movement less responsive than ground movement.

    This should provide a more natural feel to your character's motion by decelerating when not actively moving and allowing for fine-tuned control both on the ground and in the air. Adjust the friction, air_friction, and air_control values as needed to match the desired feel for your game.

  9. User

    Invalid type in utility function 'lerp'. Cannot convert argument 2 from int to float.

  10. Assistant

    The error message suggests that one of the arguments supplied to the lerp function is of an invalid type. Godot's lerp function expects both the start and end values to be floats, but it seems like an integer is being passed instead.

    Make sure you are using floats for both the start and end values when calling lerp. You might be accidentally passing 0 (an integer) instead of 0.0 (a float) as the second argument of lerp. To remedy this, you should explicitly use a float value:

    velocity.x = lerp(velocity.x, 0.0, friction * delta)
    

    Here's the corrected usage of lerp in the context of your physics processing function:

    func _physics_process(delta):
        super._physics_process(delta)
        _read_input()
        
        # Apply gravity when on a 2D map
        if current_plane == "2D":
            velocity.y += gravity * delta
            
            # Determine the appropriate friction
            var current_friction = is_on_floor() ? friction : air_friction
            
            # Apply friction to reduce horizontal velocity
            velocity.x = lerp(velocity.x, 0.0, current_friction * delta)
            
            # Move the player and process collisions
            if self is KinematicBody2D:
                velocity = move_and_slide(velocity, Vector2.UP)
                if is_on_floor():
                    velocity.y = 0
            # Handle other Entity cases as required
        else:
            # Even if not in a 2D map, we might still want to apply friction
            velocity.y = 0
            velocity.x = lerp(velocity.x, 0.0, friction * delta) # Still apply friction
    
        # ... (rest of your _physics_process function)
    

    This will ensure that the velocity.x is smoothly interpolated to 0.0 (a float) over time using the given friction or air_friction value multiplied by the delta time to give you frame rate independent deceleration.

    By properly typing your values as floats, you'll avoid type errors when calling functions like lerp. Make sure to check both the types and values you pass to functions to prevent these issues.

  11. User

    apply 2d gravity and logic if 2d tag or keep as it is if not:

    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"):
    	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()
    
  12. Assistant

    To apply 2D gravity within your script and handle logic based on whether the entity is in a 2D map tag or not, you'll need to make some adjustments to your code to ensure that gravity is only applied in this context. Additionally, you'll need to check whether the entity is allowed to jump and handle movement properly.

    Here is a modified version of your execute function that includes these considerations:

    extends Node2D
    
    # Assuming you set these variables somewhere in your Player25D or Entity class:
    # var gravity: float = 2000.0 # The gravity force applied to the entity
    # var current_plane: String = "2D" # This variable determines the current plane
    
    # Modify the execute function to suit gravity and planar condition
    func execute(s, dir = []):
    	s.velocity = Vector2(0, s.velocity.y)  # Preserving vertical velocity for gravity
    
    	# Handle 2D movement with gravity if in the 2D plane
    	if s.current_plane == "2D":
    		# Apply gravity
    		s.velocity.y += s.gravity * s.get_physics_process_delta_time()
    
    		if dir.has("left"):
    			s.velocity.x -= 1
    		if dir.has("right"):
    			s.velocity.x += 1
    
    		# You need to ensure your entity can only jump when on the floor.
    		if dir.has("jump") and s.is_on_floor():
    			s.velocity.y -= s.jump_force  # s.jump_force should be a variable representing jump impulse strength
    
    		# Normalize and apply the current_speed scalar
    		s.velocity = s.velocity.normalized() * s.current_speed
    
    		# Move and slide with the velocity, assuming we are using KinematicBody2D
    		# The 'true' argument ensures is_on_floor detects properly based on the `Vector2.UP` direction.
    		# Adjust floor_max_angle and max_slides as necessary.
    		s.velocity = s.move_and_slide(s.velocity, Vector2.UP, true, 4, deg2rad(45))
    	else:
    		# Your logic for other planes (3D, for example):
    		# Movement code here would differ and not apply gravity or be based on other mechanics
    		pass
    
    	# Handle deceleration/acceleration logic if needed here, e.g., friction or air resistance
    
    

    Notes:

    1. The initial s.velocity now preserves the vertical speed (s.velocity.y) to keep the gravity effect persistent across frames. The horizontal velocity is reset every frame based on input to start fresh with the controls.
    2. s.gravity and s.jump_force should be defined in your Player25D or Entity class, and they dictate the strength of gravity and the jump impulse, respectively.
    3. The move_and_slide method is now passed the updated s.velocity, and floor normal is set for is_on_floor to function correctly.
    4. The check for s.is_on_floor ensures jumping is only possible when the entity is on the ground, preventing mid-air jumps.
    5. In the else block, you can put your logic for planes other than "2D." This could be different based on your game design for 3D movement or any other plane types.
    6. The execute function should be called from your _physics_process function typically, and make sure the execute function is part of a class that represents abilities or actions your Entity can perform.

    Finally, adjust the execute function based on how the rest of your script is structured. This example assumes that the execute function is a method within a larger movement handling script attached to entities that can move in your game. Make sure to integrate it adequately with the rest of your classes and scripts.