Hi, I’ve set up a basic movement script in a 2d top down shooter with a virtual joystick for android using simple joystick.horizontal/vertical inputs and moving the player via
rb.MovePosition(rb.position + move * speed * Time.deltaTime);
The problem I am facing is having the player rotate the movement direction. Using atan2 yielded a result of the player rotating properly but always facing the wrong way. Trying to correct it in start() did not work. I want the player to rotate the same way it would on a pc build with mouse controls. It’s my first mobile build and any help would be greatly appreciated.
@DanteAlighieri_
Hi is first time when I post here so I don’t know how to post right. Here is my code for your game, I use it in my game just edit what you need.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Diagnostics;
public class PlayerControll : MonoBehaviour
{
[SerializeField]
private float playerSpeed = 2.0f;
[Range(0, 2f)] public float MoveLimit = 0.8f;
[Range(0, 0.5f)] public float Deadzone = 0.2f;
[Range(0, 2f)] public float RotateLimit = 1f;
public LJoystick moveJoystick;
public RJoystick rotateJoystick;
public CharacterController controller;
public RGear RGear;
public float lerpTime = 1f;
public bool GoUp;
public List<float> MyZ = new List<float>();
private void Awake()
{
GetComponent<CharacterController>();
}
private void FixedUpdate()
{
float X = moveJoystick.LHorizontal;
float Z = moveJoystick.LVertical;
float moveValue = new Vector2(moveJoystick.LHorizontal, moveJoystick.LVertical).sqrMagnitude;
if (moveValue >= MoveLimit)
{
Vector3 move = new Vector3(moveJoystick.LHorizontal , 0f, moveJoystick.LVertical).normalized;
controller.Move( move * Time.deltaTime * playerSpeed);
}
float rotValue = new Vector2(moveJoystick.LHorizontal, moveJoystick.LVertical).sqrMagnitude;
if (rotValue >= Deadzone)
{
if (RGear.R == false)
{
float heading = Mathf.Atan2(moveJoystick.LHorizontal,
moveJoystick.LVertical) * Mathf.Rad2Deg;
float angle = heading - transform.rotation.y;
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.Euler(0f, angle, 0f), Time.deltaTime * lerpTime);
//Debug.Log("Calcul = " + (heading - transform.rotation.y));
//Debug.Log("HEADING = " + heading);
}
if(RGear.R == true)
{
float heading = Mathf.Atan2(moveJoystick.LHorizontal, -moveJoystick.LVertical) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.Euler(0f, -heading, 0f), Time.deltaTime * lerpTime);
}
}
}
}