How to get Kinematicbody2D to follow mouse?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By epic_coder

I’m trying to make a KinematicBody2D follow a mouse, but instead it follows bottom-right to the mouse. Here is my code. Player animation is the name of the AnimatedSprite node I am using.

extends KinematicBody2D
signal hit # Is used to detect if player is hit by projectile
export var speed = 250  # How fast the player will move (pixels/sec).
var screen_size 
func _ready():
    screen_size = get_viewport_rect().size

var velocity = Vector2.ZERO
func _move_to_mouse(delta):
    var direction = get_global_mouse_position() - position
    position.x += 0
    position.y += 0
    move_and_collide(direction)
    if get_global_mouse_position() > position:
	    $"Player animation".flip_h = true
    else:
	    $"Player animation".flip_h = false 
func _process(delta):
print(position)
position += velocity * delta
position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.y, 0, screen_size.y)
_move_to_mouse(delta)
:bust_in_silhouette: Reply From: milddeva

I’ve tried your code and it worked fine. Maybe you unchecked the centered option in your animated sprite?

Like milddeva says, your code works correctly for me too.
When you look at your Player scene on it’s own, does it show correctly centered at 0,0?

AndyCampbell | 2020-11-29 22:12

Nope. I didn’t uncheck centered.

epic_coder | 2020-11-30 16:24

Does your sprite look centred correctly at (0,0) with the axes running thru the middle when you view the Player scene on it’s own in the editor?

AndyCampbell | 2020-11-30 16:46