PlantJumper – Input System

Control the user input can be designed in several ways. I decided to use the accelerometer

In a very simple approach and trying to keep classes decoupled. The PlayerInput only changes the Component PlayerInput

using Unity.Entities;
using UnityEngine;

public class PlayerInputSystem : ComponentSystem
{
    struct PlayerData
    {
        public readonly int Length;
        public ComponentDataArray<PlayerInput> PlayerInput;
    }

    [Inject] private PlayerData m_Data;

    protected override void OnUpdate()
    {
        float dt = Time.deltaTime;

        for (int i = 0; i < m_Data.Length; ++i)
        {
            UpdatePlayerInput(i, dt);
        }
    }

    private void UpdatePlayerInput(int i, float dt)
    {
        float dirX = Input.acceleration.x;

        float xDirection = dirX > 0 ? 1 : -1;

        m_Data.PlayerInput[i] = new PlayerInput
        {
            Direction = xDirection
        };
    }
}
public struct PlayerInput : IComponentData
{
    public float Direction;
}

Changing Player direction

Using the direction change information we can now rotate the player so it will face the direction we set using the accelerometer


using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;

public class ChangeDirectionSystem : ComponentSystem
{
    public struct Data
    {
        public readonly int Length;
        public ComponentDataArray<Player> Player;
        public ComponentDataArray<Rotation> Rotation;
        public ComponentDataArray<Velocity> Velocity;
        public ComponentDataArray<PlayerInput> PlayerInput;
    }

    [Inject] private Data m_Data;

    protected override void OnUpdate()
    {
        for (int index = 0; index < m_Data.Length; ++index)
        {
            float directionX = m_Data.PlayerInput[index].Direction;

            Velocity currentVelocity = m_Data.Velocity[index];

            m_Data.Velocity[index] = new Velocity
            {
                Value = currentVelocity.Value + 0.5f * (new float3(directionX, 0, 0))
            };

            Vector3 rotationDirection = new Vector3(0, 0, -directionX);
            m_Data.Rotation[index] = new Rotation
            {
                Value = Quaternion.LookRotation(rotationDirection, Vector3.up)
            };
        }
    }
}

A thing i noticed implementing this it is that the x velocity will be set in this system and not in the jump system.

Well, this was a very short post but behind the decision of use the accelerometer are some tests i’ve made using touch, wich i didn´t use because the touch will be used to other player moviments, as shots for example