как перенести управление wasd на андроид?Unity 3d C#
Здраствуйте, я сделал управление машиной с помошью Input.GetAxis и не знаю как перенести на мобыльные устройста.Помогите пожалуйста Вот код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class carMovement : MonoBehaviour
{
public float MotoForce; // мощьность врощения задних колес
public float SteerForce; // угол поворота передних колес
public float BreakForce; // тормоз для передних колес
public float ZADBreakForce; // тормоз для задних колес
public float MaxSpeed; // максимальная скорость
public WheelCollider WheelColliderPL;
public WheelCollider WheelColliderPP;
public WheelCollider WheelColliderZL;
public WheelCollider WheelColliderZP;
public Transform PLTransform;
public Transform PPTransform;
public Transform ZLTransform;
public Transform ZPTransform;
public GameObject PPL;
public GameObject PPP;
Vector3 TPL, TPP; // вектор поворота
void Update()
{
float v = Input.GetAxis("Vertical") * MotoForce; // ускорение колес
float h = Input.GetAxis("Horizontal") * SteerForce; // угол поворот передних колес
PLTransform.Rotate(WheelColliderPL.rpm / 60 * 360 * Time.deltaTime, 0.0f, 0.0f);
PPTransform.Rotate(WheelColliderPP.rpm / 60 * 360 * Time.deltaTime, 0.0f, 0.0f);
ZLTransform.Rotate(WheelColliderZP.rpm / 60 * 360 * Time.deltaTime, 0.0f, 0.0f);
ZPTransform.Rotate(WheelColliderZP.rpm / 60 * 360 * Time.deltaTime, 0.0f, 0.0f);
WheelColliderPL.motorTorque = v * MaxSpeed;
WheelColliderPP.motorTorque = v * MaxSpeed;
WheelColliderZL.motorTorque = v * MaxSpeed;
WheelColliderZP.motorTorque = v * MaxSpeed;
WheelColliderPL.steerAngle = h;
WheelColliderPP.steerAngle = h;
if (Input.GetKeyDown(KeyCode.Space))
{
WheelColliderPL.brakeTorque = BreakForce;
WheelColliderPP.brakeTorque = BreakForce;
WheelColliderZL.brakeTorque = ZADBreakForce;
WheelColliderZP.brakeTorque = ZADBreakForce;
}
if(Input.GetKeyUp(KeyCode.Space))
{
WheelColliderPL.brakeTorque = 0;
WheelColliderPP.brakeTorque = 0;
WheelColliderZL.brakeTorque = 0;
WheelColliderZP.brakeTorque = 0;
}
TPL = PLTransform.localEulerAngles;
TPL.y = WheelColliderPL.steerAngle; // поворот коллайдера колеса
PLTransform.transform.localEulerAngles = TPL; // поворот модели колеса
TPP = PLTransform.localEulerAngles;
TPP.y = WheelColliderPL.steerAngle;
PPTransform.transform.localEulerAngles = TPP;
if (Input.GetKey(KeyCode.Z))
{
transform.Rotate(new Vector3(180, 0, 0));
}
}
}
Ответы (1 шт):
Автор решения: KOTlK
→ Ссылка
Выдели свой инпут в отдельный интерфейс и взаимодействуй с ним.
Интерфейс:
using System;
using UnityEngine;
public interface IPlayerInput
{
event Action BrakeButtonPressed;
Vector2 MovementDirection { get; }
}
И его реализации. KeyboardInput:
using System;
using UnityEngine;
public class KeyboardInput : MonoBehaviour, IPlayerInput
{
public event Action BrakeButtonPressed;
[SerializeField] private KeyCode _brakeButton = KeyCode.Space;
public Vector2 MovementDirection => DefineDirection();
private void Update()
{
WaitForBrakeButton();
}
private void WaitForBrakeButton()
{
if (Input.GetKeyDown(_brakeButton))
{
BrakeButtonPressed?.Invoke();
}
}
private Vector2 DefineDirection()
{
var x = Input.GetAxis("Horizontal");
var y = Input.GetAxis("Vertical");
return new Vector2(x, y);
}
}
и MobileInput:
using System;
using UnityEngine;
using UnityEngine.UI;
public class MobileInput : MonoBehaviour, IPlayerInput
{
public event Action BrakeButtonPressed;
[SerializeField] private Button _brakeButton = null;
[SerializeField] private ScreenJoystick _joystick = null;
public Vector2 MovementDirection => _joystick.Delta;
private void OnEnable()
{
_brakeButton.onClick.AddListener(() => BrakeButtonPressed?.Invoke());
}
private void OnDisable()
{
_brakeButton.onClick.RemoveListener(() => BrakeButtonPressed?.Invoke());
}
}
Далее взаимодействуй с интерфейсом, а не конкретной реализацией:
using UnityEngine;
public class SomeBehaviour : MonoBehaviour
{
[SerializeField] private MonoBehaviour _input = null;
private IPlayerInput PlayerInput => (IPlayerInput)_input;
private void OnValidate()
{
if (_input is IPlayerInput) return;
Debug.LogError($"{nameof(_input)} should implement {nameof(IPlayerInput)}");
_input = null;
}
private void OnEnable()
{
PlayerInput.BrakeButtonPressed += DebugBrake;
}
private void OnDisable()
{
PlayerInput.BrakeButtonPressed -= DebugBrake;
}
private void Update()
{
Debug.Log(PlayerInput.MovementDirection);
}
private void DebugBrake()
{
Debug.Log("Brake");
}
}
То есть в твоем carMovement не должно быть проверок на нажатие кнопок / GetAxis и т.п. У тебя есть IPlayerInput, все взаимодействие через него.
Теперь абсолютно не важно с какой платформы ты играешь, можно в PlayerInput подставить что угодно, лишь бы оно реализовывало IPlayerInput.