Skip to content

Instantly share code, notes, and snippets.

@arcueid-dev
Created May 10, 2022 11:45
Show Gist options
  • Select an option

  • Save arcueid-dev/21231dfcd4fa636fa53bd97d4c246e8f to your computer and use it in GitHub Desktop.

Select an option

Save arcueid-dev/21231dfcd4fa636fa53bd97d4c246e8f to your computer and use it in GitHub Desktop.
Acceleration Move example calculations
using System;
using UnityEngine;
public interface IMovable
{
public Vector3 Forward { get; }
public Vector3 Position { get; }
public void Move(Vector3 vector3);
}
[Serializable]
public class TransformMovable : IMovable
{
[SerializeField] private Transform movableTransform;
public Vector3 Forward => movableTransform.forward;
public Vector3 Position => movableTransform.position;
public void Move(Vector3 vector3)
{
movableTransform.position = vector3;
}
}
public class AccelerationMove : MonoBehaviour
{
[SerializeField] private float speed = 5f;
[SerializeField] private float accelerationSpeed = 1f;
[SerializeReference] private IMovable movable = new TransformMovable();
private float acceleration = 0f;
// Update is called once per frame
private void Update()
{
var input = Input.GetAxis("Vertical");
if (acceleration > 0)
{
movable.Move(movable.Position + movable.Forward * speed * input * Time.deltaTime * acceleration);
}
var f = Time.deltaTime * accelerationSpeed;
acceleration += f * (Mathf.Abs(input) > 0 ? 1 : -1);
acceleration = Mathf.Clamp01(acceleration);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment