Plant Jumper – Player Moviment

The player moviment using ECS as another systems must be designed to be data driven.

At the beginning our player will jump and change direction. So we need the following components

Position – will describe its position
Heading2D – will describe if it is pointing right ou left
Velocity – will describe the jump and fall moviment

Auto Jump System

In the jumpter game, the player is always jumping, so i created an auto jump system


using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;

using Unity.Mathematics;


[UpdateAfter(typeof(ComputeColliderAABBSystem))]
public class AutoJumpSystem : ComponentSystem
{
    public struct Data
    {
        public readonly int Length;
        public ComponentDataArray<Heading> Heading;
        public ComponentDataArray<Player> Player;

        public ComponentDataArray<Velocity> Velocity;

        public ComponentDataArray<CollisionComponent> CollisionComponent;

    }

    [Inject] private Data m_Data;

    public AutoJumpSystem()
    {
    }

    private float amountY = 20;
    private float amountX = 5;
    protected override void OnUpdate()
    {
        for (int index = 0; index < m_Data.Length; ++index)
        {
            if (m_Data.CollisionComponent[index].Value > 0)
            {
                float3 velocity = new float3(0, amountY, 0);
                velocity += (amountX * m_Data.Heading[index].Value);

                m_Data.Velocity[index] = new Velocity { Value = velocity };
            }
        }
    }
}

As you can noticed we are not changing position, just the velocity data. This is due to the RigidBody system been already treating velocity changes, but for that i have to make a little change in the rigidbody system

protected override void OnUpdate()
    {
        float dt = Time.deltaTime;
        for (int index = 0; index < m_Data.Length; ++index)
        {
            float3 gravity = new float3(0, -20, 0);

            var position = m_Data.Position[index].Value;
            if (m_Data.Collision[index].Value > 0)
            {
                gravity = float3.zero;
            }

            Velocity velocity = new Velocity
            {
                Value = m_Data.Velocity[index].Value + gravity * dt
            };
            m_Data.Velocity[index] = velocity;

            position += (m_Data.Velocity[index].Value * dt + 0.5f * gravity * dt * dt);

            m_Data.Position[index] = new Position { Value = position };
        }
    }

The method onUpdate now will apply the velocity every cicle and if there is a collision, not apply gravity. I know this is a very simple aproximation but for this game, it is enough.