'Joystick movement works on editor but not on mobile
I want to make a joystick controller for movement I created 2 script for this player move and joystick script, but I have a problem joystick movement works perfectly on editor but on mobile it's not working, joystick is still working but my character is not moving
Here's my script:
player move:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerMoveController : MonoBehaviour
{
public GameObject player;
private CharacterController _charController;
private float inputX;
private Transform meshPlayer;
private float inputZ;
private Vector3 v_movement;
private float moveSpeed;
public ManagerJoystick _mngrJoystick;
// Start is called before the first frame update
void Start()
{
moveSpeed = 1;
meshPlayer = player.transform.GetChild(0);
GameObject tempPlayer = GameObject.FindGameObjectWithTag("Player");
_charController = player.GetComponent<CharacterController>();
_charController = tempPlayer.GetComponent<CharacterController>();
}
void Update()
{
inputX = _mngrJoystick.inputHorizontal();
inputZ = _mngrJoystick.inputVertical();
}
void FixedUpdate()
{
v_movement = new Vector3(inputX * moveSpeed, 0, inputZ * moveSpeed);
_charController.Move(v_movement);
}
}
joystick controller:
public class ManagerJoystick : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
{
private Image imgJoystickBg;
private Image imgJoystick;
private Vector2 posInput;
private void Start()
{
imgJoystickBg = GetComponent<Image>();
imgJoystick = transform.GetChild(0).GetComponent<Image>();
}
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
imgJoystickBg.rectTransform,
eventData.position,
eventData.pressEventCamera,
out posInput))
{
posInput.x = posInput.x / (imgJoystickBg.rectTransform.sizeDelta.x);
posInput.y = posInput.y / (imgJoystickBg.rectTransform.sizeDelta.y);
Debug.Log(posInput.x.ToString());
//normalize
if (posInput.magnitude > 1.0f)
{
posInput = posInput.normalized;
}
//joystick move
imgJoystick.rectTransform.anchoredPosition = new Vector2(
posInput.x * (imgJoystickBg.rectTransform.sizeDelta.x) / 4,
posInput.y * (imgJoystickBg.rectTransform.sizeDelta.y) / 4);
}
}
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
posInput = Vector2.zero;
imgJoystick.rectTransform.anchoredPosition = Vector2.zero;
}
public float inputHorizontal()
{
if (posInput.x != 0)
return posInput.x;
else
return Input.GetAxis("Horizontal");
}
public float inputVertical()
{
if (posInput.x != 0)
return posInput.y;
else
return Input.GetAxis("Vertical");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
