Need help with making movement direction the same as the camera rotation

I’m not sure how to do it, I’ve used sin & cos (probably incorrectly) and I directly translated other resources, and all I got was something that “worked” but had a LOT of flaws (like not going in the right direction.)

code:

	 public override void _UnhandledInput(InputEvent @event)
    {
		float maxRot = 3.14 * 0.5; 
		Vector3 rot = cam.Rotation;

		if (interfaceMode == false && @event is InputEventMouseMotion eventMouseMotion)
		{
			rot.X += Mathf.Clamp(eventMouseMotion.Relative.Y * sensitivity, maxRot * -1, maxRot);
			rot.Y += eventMouseMotion.Relative.X * sensitivity;
		}
		
		cam.Rotation = rot;
    }

    public override void _PhysicsProcess(double delta)
    {
		Vector3 rot = character.Rotation;

		rot.Y = cam.Rotation.Y;
		character.Rotation = rot;

		Vector2 input = Input.GetVector("move_left", "move_right", "move_back", "move_forward");
		Vector3 direction = character.Rotation.Y * new Vector3(input.X, 0.0f, input.Y);
		Vector3 position = Vector3.Zero;

		if (character.IsOnFloor() != true)
		{
			position.Y -= grav * (float)delta;
		}

		if (Input.IsActionJustPressed("jump") && character.IsOnFloor())
		{
			position.Y += jumpHeight * (float)delta;
		}

		if (direction != Vector3.Zero)
		{
			direction.Z = Mathf.Clamp(direction.Z, -1, 1);
			direction.X = Mathf.Clamp(direction.X, -1, 1);
			velocity += acceleration * (float)delta;

			position.X = Mathf.Clamp(direction.X * velocity, terminalVelocity * -1f, terminalVelocity);
			position.Z = Mathf.Clamp(direction.Z * velocity, terminalVelocity * -1f, terminalVelocity);
		}
		
		character.MoveAndCollide(position * (float)delta, false, 0.001f, true, 5);
    }

This doesn’t rotate a vector, Rotation.Y is a float value so it’s similar to multiplying by 0 to PI. You could use the Vector3’s .rotated function or a matrix multiplication by the camera’s transform.

I don’t like C# so I’m guessing it would be like so for a matrix multiplication.

Vector3 direction = character.Basis * new Vector3(input.X, 0.0f, input.Y);

You will not need to clamp the direction after this change.

1 Like

It worked for the most part, but another issue i’m running into is that the velocity does not reflect direction.

You can use PI, as a value. Its a variable, but defined by the engine