SOLVED:
When I made the post I was using different code for player movement and attack, I switched to using animationTrees and learned of the position.direction.to_(get_global_mouse_position) code!

	if(Input.is_action_just_pressed("Attack")): #input for attacking, the position of the mouse is then acquired and placed on the attackDirection var
		attackDirection = position.direction_to(get_global_mouse_position()) #gets your mouse position relative to the player
		animation_tree["parameters/conditions/attack"] = true
		animation_tree["parameters/Attack/blend_position"] = attackDirection #Plays the attack aniamtion blend position with the blend position value from the attackDirection
	else:
		animation_tree["parameters/conditions/attack"] = false #no longer attacking
		
	if(moveDirection != Vector2.ZERO):
		animation_tree["parameters/Idle/blend_position"] = moveDirection
		animation_tree["parameters/Walk/blend_position"] = moveDirection

Hi!
I'm working on a top down pixel action RPG and I'm entirely new to godot and coding.

The controls I'm trying to work on are as follows:
- Player sprite moves and faces camera / 4 directional movement
- Player sprite attacks in the direction of camera (example control: welcome to the gungeon), it's not just one attack but with combos and skills in the future.
- If player is moving left but mouse is on the right side: Player sprite that's on walking / running animation should still face mouse.
- If player dodge rolls, they dodge in the direction they're moving, not the camera face. (not in the code yet)

What I want to do:

  • Have Player Sprite play the appropriate directional idle / walk when mouse is at a certain point to "face it" - this comes alongside the attacks.
    EDIT: New idea: Have Player Sprite instead play the appropriate directional attack if I were to keep it simple, just keeping it in here.

Q: "How will I make it so that the player sprite faces the same direction of the mouse cursor, and attack in the same direction you left click?"

The details of what I've done so far:

  • AnimatedSprite2D for the sprite and AnimationPlayer for animations.
  • AnimationPlayer contains 12 different animations: 4 directional idles , 4 directional basic attack and 4 directional walks. They're named Idle, Attack and Walk but with the initial of the direction with underscore (example: L_Walk for left walk)

This is old code:

Click to reveal Click to hide
extends CharacterBody2D
class_name PlayerMain

var basespeed: int = 200 #speed
var previousDirection = "R_" #Variable for storing previousDirection
var direction = "R_" #CurrentDirection
var mouse_direction: Vector2 = (get_global_mouse_position() - global_position).normalized() #attempt for mouse direction
var AttackIP: bool = false #Attack InProgress

@onready var animation = $PlayerAnims

#PLAYER MOVEMENT CODE
func handleInput():
	var moveDirection = Input.get_vector("Move_Left","Move_Right", "Move_Up", "Move_Down")
	velocity = moveDirection * basespeed
	
	if Input.is_action_just_pressed("Attack"):
		animation.play(previousDirection + "Attack")
		AttackIP = true
		await animation.animation_finished
		AttackIP = false

func updateAnimation():
	if AttackIP: return
	
	if velocity.x < 0: direction = "L_";previousDirection = "L_" #Means if going left, direction becomes L
	elif velocity.y < 0: direction = "U_";previousDirection = "U_" #Up, direction becomes U
	elif velocity.y > 0: direction = "D_";previousDirection = "D_" #Down, direction becomes D
	elif velocity.x > 0: direction = "R_";;previousDirection = "R_" #Right, direction becomes R
	if velocity.length() == 0: #Stop
		animation.play(previousDirection + "Idle") #The last direction acquired from the else call
	else:
		animation.play(direction + "Walk") #PlayerAnims has the animation timeline name  

#func mousemove():
#	if mouse_direction.x > 0 and animation.current_animation == "L_Idle" and velocity.length() == 0:
#		animation.play("R_Idle")
#	elif mouse_direction.x < 0 and not animation.current_animation == "L_Idle" and velocity.length() == 0:
#		animation.play("L_Idle")

func _physics_process(_delta):
	handleInput()
	move_and_slide()
	updateAnimation()

This is the Player Scene Tree:

The func mousemove that's in comments was a test to try and use mouse.direction to see if player will look left and right, it did not work but I thought to keep it in here in case I learn something about it.

I also apologize for the excess comments as they're there for me to really get it in my head to understand. (I'm a slow visual learner)

For further info that may help I also followed this tutorial: Tutorial by Maker Tech

    Xyrenity I also apologize for the excess comments as they're there for me to really get it in my head to understand. (I'm a slow visual learner)

    Don't apologize, it's your code so write whatever you want and need. 👍

    Can you show a small video clip of what you have so far? Also do you have a specific question or problem? It's easier for people unfamiliar with your code to answer precise and specific questions.

      Toxe
      Ah I've given what I want to do but not necessarily the specific question now did I? Got carried away! xD

      Q: "How will I make it so that the player sprite faces the same direction of the mouse cursor, and attack in the same direction you left click?"
      I'd like to also say that hours after I made the post I also thought it might be simpler and easier to just have the player face the same direction of the mouse when they're attacking instead, so I was hoping I could ask for some help on that as well in the case I do decide on which to do if viable.

      (Updated main post)
      Here is a small clip, I did very quick stick figure assets just to focus on the coding and testing .

      • Toxe replied to this.

        Xyrenity Looks cute. 😄

        How top-down is this going to be? 100% top-down or more or less isometric?

        If it's 100% top-down then I would spontaneously think of two options:

        Option 1: Always rotate the player so that you look towards the mouse. If you shoot or fire you play the corresponding animation and because you are already rotated in the right direction it will look good. Downside: If the character is human and needs proper animations depending on whether it moves forward, backwards, sidewards or diagonally this would look bad. But it could work for some kind of levitating robot. Also it would be a start to get going.

        Option 2: Build the player out of two sprites, a top one for the body and a lower one for the legs. (Or think like tank body and turret.) Always rotate the upper body towards the mouse and then find some logic for the lower parts with the legs. You could just rotate the legs towards your movement direction but again this could look terrible because a human would walk sideways and not just twist their legs in some weird way.

        But you can overcome this by making different animations for moving forward, backward, sideways and diagonally and then pick the correct one depending on the directions you look and move.

        Probably best to look at some top-down games on how they are handling this. I have never done this before either so there is a chance that I am talking complete rubbish, but at least it should be something to get you started.😉

          Toxe
          Isometric! Example games are Cult of the Lamb and Guardian Tales, but the style direction I'm going for are sprite animations going in the four directions only with moving diagonally prioritizing left / right animations, nothing of the full top down or the sort (this means I'm also going for frame by frame pixel animations so nothing like the option 2) Just need to know how to code getting the mouse direction and applying it with the code I got, but as of writing this I've changed the code to using AnimationTrees instead!

          • Toxe replied to this.

            Xyrenity Getting the direction to the mouse cursor is simple. Basically something like position.direction_to(get_global_mouse_position()).

            https://docs.godotengine.org/en/latest/tutorials/2d/2d_movement.html#click-and-move

            If you want to rotate towards the mouse look at this example:

            https://docs.godotengine.org/en/latest/tutorials/2d/2d_movement.html#rotation-movement-mouse

              Toxe

              Thank you so so much! It worked! Instead of having the player face the mouse I opted to have the player attack in the same direction, as to me it feels right that way with the vision I now have. (+ I won't have to animate characters hopping back since Im planning character 'switching' in the future)

              I will update post with the code I was using since I opted for animationtree which made things a lot simpler.