94 lines
2.1 KiB
C#
94 lines
2.1 KiB
C#
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(CharacterController))]
|
|
public class CameraRelativeControl : MonoBehaviour
|
|
{
|
|
public Joystick moveJoystick;
|
|
|
|
public Joystick rotateJoystick;
|
|
|
|
public Transform cameraPivot;
|
|
|
|
public Transform cameraTransform;
|
|
|
|
public float speed = 5f;
|
|
|
|
public float jumpSpeed = 8f;
|
|
|
|
public float inAirMultiplier = 0.25f;
|
|
|
|
public Vector2 rotationSpeed = new Vector2(50f, 25f);
|
|
|
|
private CharacterController character;
|
|
|
|
private Vector3 velocity;
|
|
|
|
private bool canJump = true;
|
|
|
|
private void Start()
|
|
{
|
|
character = GetComponent<CharacterController>();
|
|
GameObject gameObject = GameObject.Find("PlayerSpawn");
|
|
if (gameObject != null)
|
|
{
|
|
base.transform.position = gameObject.transform.position;
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
Vector3 motion = cameraTransform.TransformDirection(new Vector3(moveJoystick.position.x, 0f, moveJoystick.position.y));
|
|
motion.y = 0f;
|
|
motion.Normalize();
|
|
Vector2 vector = new Vector2(Mathf.Abs(moveJoystick.position.x), Mathf.Abs(moveJoystick.position.y));
|
|
motion *= speed * ((!(vector.x > vector.y)) ? vector.y : vector.x);
|
|
if (character.isGrounded)
|
|
{
|
|
if (!rotateJoystick.IsFingerDown())
|
|
{
|
|
canJump = true;
|
|
}
|
|
if (canJump && rotateJoystick.tapCount == 2)
|
|
{
|
|
velocity = character.velocity;
|
|
velocity.y = jumpSpeed;
|
|
canJump = false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
velocity.y += Physics.gravity.y * Time.deltaTime;
|
|
motion.x *= inAirMultiplier;
|
|
motion.z *= inAirMultiplier;
|
|
}
|
|
motion += velocity;
|
|
motion += Physics.gravity;
|
|
motion *= Time.deltaTime;
|
|
if (character.enabled)
|
|
{
|
|
character.Move(motion);
|
|
}
|
|
if (character.isGrounded)
|
|
{
|
|
velocity = Vector3.zero;
|
|
}
|
|
FaceMovementDirection();
|
|
Vector2 position = rotateJoystick.position;
|
|
position.x *= rotationSpeed.x;
|
|
position.y *= rotationSpeed.y;
|
|
position *= Time.deltaTime;
|
|
cameraPivot.Rotate(0f, position.x, 0f, Space.World);
|
|
cameraPivot.Rotate(position.y, 0f, 0f);
|
|
}
|
|
|
|
private void FaceMovementDirection()
|
|
{
|
|
Vector3 vector = character.velocity;
|
|
vector.y = 0f;
|
|
if ((double)vector.magnitude > 0.1)
|
|
{
|
|
base.transform.forward = vector.normalized;
|
|
}
|
|
}
|
|
}
|