I have tried searching everywhere but for whatever reason I cannot seem to find a solution for this. My joystick is a simple UI joystick made from knobs and it functions well but I cannot seem to get my charactercontroller to move with the movement of the joystick. Here is the script on the joystick:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgjoystick;
private Image Joybutton;
private Vector3 inputVector;
private void Start()
{
bgjoystick = GetComponent<Image>();
Joybutton = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if(RectTransformUtility.ScreenPointToLocalPointInRectangle(bgjoystick.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x / bgjoystick.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgjoystick.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
Joybutton.rectTransform.anchoredPosition = new Vector3(inputVector.x * (bgjoystick.rectTransform.sizeDelta.x / 3), inputVector.z * (bgjoystick.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
inputVector = Vector3.zero;
Joybutton.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}
and this is the code on the charactercontroller (testing on primitive sphere)
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class MovementJack : MonoBehaviour {
public float movespeed = 50.0F;
public float drag = 0.5F;
public float terminalRotationSpeed = 25.0f;
public float gravity;
public Vector3 MoveVector { set; get; }
public VirtualJoystick JoyStick;
private Rigidbody controller;
private Transform camTransform;
void Start()
{
controller = GetComponent<Rigidbody>();
controller.maxAngularVelocity = terminalRotationSpeed;
controller.drag = drag;
}
void Update()
{
MoveVector = PoolInput();
Move();
// controller.AddForce(dir * movespeed);
//
}
private void Move()
{
controller.AddForce((MoveVector * movespeed));
controller.AddForce(Vector3.down * gravity * controller.mass);
}
private Vector3 PoolInput()
{
Vector3 dir = Vector3.zero;
dir.x = JoyStick.Horizontal(); //dir.x = Input.GetAxis("Horizontal");
dir.z = JoyStick.Vertical(); //dir.z = Input.GetAxis("Vertical");
if (dir.magnitude > 1) dir.Normalize();
return dir;
}
}
Any help greatly appreciated, thanks.