Description
I’ve seen some Unity tutorials and I’m trying to apply good practices to modularize the code. However, I’m running into some issues while trying to use rigidBody2d.MovePosition()
.
I have two classes: Player
(which defines rules and performs calculations) and PlayerController
(uses computed data from Player
to interact with Unity itself).
Player.cs
using UnityEngine;
public class Player
{
public Vector2 MoveTowards(Vector2 currentPosition, Vector2 direction)
{
return currentPosition + direction * 2f;
}
}
PlayerController.cs
using UnityEngine;
(RequireComponent(typeof(Rigidbody2D)))
(RequireComponent(typeof(Animator)))
public class PlayerController : MonoBehaviour
{
public Player player;
Rigidbody2D rb2d;
Vector2 movementDirection = Vector2.zero;
void Awake()
{
player = new Player();
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
movementDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
void FixedUpdate()
{
rb2d.MovePosition(player.MoveTowards(rb2d.position, movementDirection) * Time.fixedDeltaTime);
}
}
What happens visually is the player’s sprite moves (just a tiny bit) towards the given direction and goes back to (x: 0, y: 0) as soon as I release the movement key.
Player on Inspector:
What I tested
Inside FixedUpdate
, it does not work when I use:
rb2d.MovePosition(player.MoveTowards(rb2d.position, movementDirection) * Time.fixedDeltaTime);
Inside FixedUpdate
, it does not work when I use:
Vector2 controllerNewPosition = rb2d.position + movementDirection * 2f;
rb2d.MovePosition(controllerNewPosition * Time.fixedDeltaTime);
Inside FixedUpdate
, it works when I use:
rb2d.MovePosition(rb2d.position + movementDirection * 2f * Time.fixedDeltaTime);
Questions
Maybe that is being caused by the operator +
and not creating a new Vector2, instead mutating rb2d.position
? While I’m not new to programming, I have no experience with C#, so I don’t know the specifics of the syntax yet.
How could I use player.MoveTowards
in this case?
Feeling dumb. Right after publishing the question I realized the glaring mathematical priority issue. I’ve been debugging this for hours. I guess it happens to everyone.