Help with changing gravity/physics depending if in water

Godot Version

4.1.1 stable


I have been trying to create a code for when a CharacterBody2D enters water that changes the gravity if in water and if out heres my code.
ps sorry my layout is a bit bad im really new to godot

extends CharacterBody2D
class_name Player

var SPEED = 300.0
var JUMP_VELOCITY = -400.0
var isinwater = false
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
func inwater():
SPEED = 200
gravity = 0
isinwater = true

func _physics_process(delta):
# Add the gravity.

if not isinwater:
	if not is_on_floor():
		velocity.y += gravity * delta

	# Handle Jump.
	if Input.is_action_just_pressed("Up") 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("Left", "Right")
	if direction:
		velocity.x = direction * SPEED
		velocity.x = move_toward(velocity.x, 0, SPEED)
	if Input.is_action_pressed("Down"):
		velocity.y += 10
	if Input.is_action_pressed("Up"):
		velocity.y -= 10
	if Input.is_action_pressed("Right"):
		velocity.x += 10
	if Input.is_action_pressed("Left"):
		velocity.x -= 10

And this is my code for “water” which is a area 2d

extends Area2D
class_name Water

signal inwater

func _on_body_entered(body):
if body is Player:

Just make an area 2d where the water is and then a variable called something like gravity modifier. Something like this.

Var grav_modifier = 1

Var gravity =ProjectSettings.get_setting(“physics/2d/default_gravity”) * grav_modifier

#add the rest of your code

On area2d body entered
Grav_modifier =0.5 #change this to what you want

Add your code and edit this to what you need.
I hope this helps.

This is the simplest way to do it. I use this in my own game.

Looks like you’ve got a great start, what isn’t working? Could you describe what is happening in game?

When pasting code make sure to place it between three ticks like so, the </> tool or ctrl+e will create these three ticks for you

type or paste code here

To me it just seems you are missing a body_exited connection for leaving the water.

this works but i also want to change the controls.
also when i load up the game with the intial code there is no controls or graity and the player just stands there

when i boot up the game there is no controls and gravity so the charecter just floats there. im trying to make it so that when in water there are totaly new controls and gravity

Could you show your scene tree? are there any errors?

It’s a problem I have had too in my game once the gravity changes it works again so I guess you could try build some kind of check to see if the player is in the area

The controls could be done in a similar way but changing the controls

The error has been fixed thanks for your help