Skip to content

Instantly share code, notes, and snippets.

@bengsfort
Created July 5, 2017 19:37
Show Gist options
  • Save bengsfort/f3bd47490f7c33da176af606738bbefd to your computer and use it in GitHub Desktop.
Save bengsfort/f3bd47490f7c33da176af606738bbefd to your computer and use it in GitHub Desktop.
example of bare bones ECS implementation with MonoBehaviours
// PlayerComponent
using System;
using UnityEngine;
using Bengsfort.Components.Core;
namespace Bengsfort.Components
{
[Serializable]
public class PlayerComponent : BaseComponent
{
public Rigidbody2D rigidbody;
public SpriteRenderer renderer;
}
}
using UnityEngine;
using Bengsfort.Components;
using Bengsfort.Entities.Core;
using Bengsfort.Systems;
namespace Bengsfort.Entities
{
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(PolygonCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerEntity : BaseEntity
{
[Header("Player Settings")]
public PlayerComponent player;
public ThrustMovementComponent thrustMovement;
public SpawnPointComponent spawn;
public InputComponent input;
private InputSystem m_Input;
private RespawnSystem m_Respawn;
private ThrustMovementSystem m_Thrust;
private RestrictToViewportSystem m_RestrictToView;
void Start()
{
m_Input = new InputSystem();
m_Respawn = new RespawnSystem(spawn);
m_Thrust = new ThrustMovementSystem(thrustMovement);
m_RestrictToView = new RestrictToViewportSystem(player);
}
void Update()
{
m_Respawn.Tick();
if (m_Input.active)
m_Input.Tick();
if (m_Thrust.active)
m_Thrust.Tick();
m_RestrictToView.Tick();
}
void FixedUpdate()
{
if (m_Thrust.active)
m_Thrust.FixedTick();
m_RestrictToView.Tick();
}
}
}
using UnityEngine;
using Bengsfort.Systems.Core;
using Bengsfort.Components;
namespace Bengsfort.Systems
{
public class RestrictToViewportSystem : BaseSystem
{
private PlayerComponent m_Player;
public override void Tick()
{
var center = Camera.main.WorldToScreenPoint(m_Player.renderer.bounds.center);
var movement = m_Player.rigidbody.velocity;
if (center.x < 0.0f)
movement.x = Mathf.Max(movement.x, 0.0f);
if (center.x > Camera.main.pixelWidth)
movement.x = Mathf.Min(movement.x, 0.0f);
m_Player.rigidbody.velocity = movement;
}
public RestrictToViewportSystem(PlayerComponent player)
{
m_Player = player;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment