How to have smooth 2d player movement and rotation for android unity?,How to have a smooth player 2d movement with rotation in the speed, where the camera follows the player using joystick controls?
I am a beginner and working on 2d game development.
My goal is to have the player constantly moving in the joystick direction at the constant speed, in the same direction. Thus, if the 2D player sprite is moving in +x direction, and the player points the joystick in the -x direction. The 2D player rotates towards -x direction and starts moving in that direction.
Currently, to perform the above step, I created an empty gameobject, with the camera and player sprite as the child components. As the joystick is moved, the parent gameobject is moved, while the player sprite is supposed to be rotated in the direction of the new joystick direction.
I tried the following code for the parent gameobject:
protected Joystick _joystick;
private Vector3 _velocity;
[SerializeField]
private float _speed = 3.5f;
public int speedPowerupMultiplier = 1;
// Start is called before the first frame update
void Start()
{
_joystick = FindObjectOfType<Joystick>();
transform.position = Vector3.zero;
_velocity = new Vector3(0f, _speed * Time.deltaTime, 0f);
}
// Update is called once per frame
void Update()
{
if (!(_joystick.Horizontal == 0f && _joystick.Vertical == 0f))
{
float joyStickSpeedAvgd = (float)Math.Sqrt(Math.Pow(_joystick.Horizontal, 2) + Math.Pow(_joystick.Vertical, 2));
_velocity = new Vector3(_joystick.Horizontal * _speed * speedPowerupMultiplier * Time.deltaTime / joyStickSpeedAvgd,
_joystick.Vertical * _speed * speedPowerupMultiplier * Time.deltaTime / joyStickSpeedAvgd,
0f);
}
transform.Translate(_velocity);
}
In the player, I did the following:
private void FixedUpdate()
{
float rotateVertical = _joystick.Vertical * 3.5f;
float rotateHorizontal = _joystick.Horizontal * -3.5f;
transform.Rotate(0f, 0f, Mathf.Atan2(rotateVertical, rotateHorizontal));
}
Would be really helpful, if someone could tell me the best idea on implementing this
Your answer
Follow this Question
Related Questions
How to rotate sword while still looking at mouse? 1 Answer
how can i anchor a point of a sprite to make it swing? 1 Answer
Linear speed in one direction 0 Answers
Factorio-like sprite directions 0 Answers