TriggerFox Games
TriggerFox Games

Reputation: 31

Godot smooth 2d player movement script errors

I'm trying to program top-down player movement for my game, and im getting errors that are probably a really simple fix, but im new to godot, and need help. my code is:


const SPEED = 200
const FRICTION = 5
const DASH_SPEED = 400
const DASH_DURATION = 0.1
const DASH_COOLDOWN = 1.5

var velocity = Vector2.ZERO
var dashTimer = 0
var canDash = true

func _physics_process(delta: float) -> void:
    # Player movement
    var inputVector = Vector2.ZERO
    if Input.is_action_pressed("ui_up"):
        inputVector.y -= 1
    if Input.is_action_pressed("ui_down"):
        inputVector.y += 1
    if Input.is_action_pressed("ui_left"):
        inputVector.x -= 1
    if Input.is_action_pressed("ui_right"):
        inputVector.x += 1

    # Apply friction
    if inputVector == Vector2.ZERO:
        velocity = velocity.linear_interpolate(Vector2.ZERO, FRICTION * delta)
    else:
        velocity += inputVector.normalized() * SPEED * delta

    # Perform dash
    if canDash and Input.is_action_just_pressed("dash"):
        var dashDirection = get_global_mouse_position() - position
        var dashDistance = dashDirection.length()
        if dashDistance > 0:
            dashDirection = dashDirection.normalized()
            velocity = dashDirection * DASH_SPEED
            dashTimer = DASH_DURATION
            canDash = false

    # Apply dash cooldown
    if not canDash:
        dashTimer -= delta
        if dashTimer <= 0:
            canDash = true

    # Move the player
    linear_velocity = velocity

the two errors are:

Line 9:Member "velocity" redefined (original in native class 'CharacterBody2D')Line 48:Identifier "linear_velocity" not declared in the current scope.

I've tried looking around on tutorials, and they all seem to use this method, any help?

Upvotes: 1

Views: 1410

Answers (1)

Theraot
Theraot

Reputation: 40220

  1. linear_velocity is a property of rigid bodies, you are not using a rigid body.

    So don't do this: linear_velocity = velocity

  2. velocity is a property of character bodies, you are using a character body, you don't need to define velocity.

    So, remove this: var velocity = Vector2.ZERO

    Note: character bodies are the Godot 4 replacement for Godot 3 kinematic bodies, for which you had to define your own velocity.

I'm guessing you have been mixing tutorials.


After fixing that you will find that your character does not move. This is because you are responsible for moving character bodies (unlike rigid bodies, for which the responsibility of moving them falls to the physics system of Godot).

The usual way to make to make your character body move is by calling move_and_slide. In Godot 3 you would have to pass the velocity as an argument, but in Godot 4 the velocity is a property, which you just set some time before calling move_and_slide.

Upvotes: 3

Related Questions