Move Character Body with Mouse

Godot Version

4.2.1 (mono)

Question

Hey, I want to move a Character Body by the relative vector of the InputEventMouseMotion (docs) event but I want the character body to still collide with other physic bodies. Is there a way to accomplish this?

extends CharacterBody2D

const SPEED = 100.0

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		var mouse_motion := event as InputEventMouseMotion
		velocity = mouse_motion.relative * SPEED

func _physics_process(_delta: float) -> void:
	move_and_slide()

I thought of that but it doesn’t work, since I need the object to move exactly like the mouse and it should not be off like it would with this approach…

extends CharacterBody2D

const SPEED := 50.0

func _physics_process(_delta: float) -> void:
	var mouse_pos := get_global_mouse_position()
	var diff := mouse_pos - global_position
	velocity = diff * SPEED
	move_and_slide()

I got another solution but thanks :smiley:

this works exactly like I want it to

extends CharacterBody2D

var relative: Vector2

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		relative = event.relative


func _physics_process(delta: float) -> void:
	move_and_collide(relative)
	relative = Vector2.ZERO

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.