This is an implementation of a playerController "joystick" script, its working ok with 1 problem, as I move the clamped pad position around its parent image, my player object moves as you would expect. The issue arises when I spin the camera, the movement does not take into account the direction the camera is facing, so movement then is pretty much in reverse. I know I need a reference to my cameras current forward facing position, Im just not sure where this needs to sit in the below script, any tips would be great !
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
public Transform player;
Vector3 move;
public float moveSpeed;
private Transform cameraTransform; //ref to main camera, then needs to manipulate the direction somehow.
public RectTransform pad;
private void Start()
{
cameraTransform= Camera.main.transform;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = eventData.position;
transform.localPosition =
Vector2.ClampMagnitude(eventData.position - (Vector2)pad.position, pad.rect.width * 0.5f);
move.y = 0;
move = (cameraTransform.forward * transform.localPosition.x cameraTransform.right * transform.localPosition.z).normalized;
}
public void OnPointerUp(PointerEventData eventData)
{
transform.localPosition = Vector3.zero;
move = Vector3.zero;
StopCoroutine("PlayerMove");
}
public void OnPointerDown(PointerEventData eventData)
{
StartCoroutine("PlayerMove");
}
IEnumerator PlayerMove()
{
while(true)
{
player.Translate(move * moveSpeed * Time.deltaTime, Space.World);
if (move!= Vector3.zero)
player.rotation = Quaternion.Slerp(player.rotation, Quaternion.LookRotation(move), 5* Time.deltaTime);
yield return null;
}
}
}
CodePudding user response:
Replacing the move direction calculation with the following should work.
move = (cameraTransform.forward * transform.localPosition.x cameraTransform.right * transform.localPosition.z).normalized;
To understand why this works remember your default forward direction is Vect3(1.0, 0.0, 0.0) and your right direction is Vect3(0.0, 0.0, 1.0) meaning as long as we don't turn we get your original calculation. Once we start turning we basically rotate the pad movement by the y angle we're rotated by.
If your player is not supposed to move on the y axis make sure to set the y component of the move vector to 0 before normalizing it.