Skip to content

Instantly share code, notes, and snippets.

@madTeddy
Created October 31, 2023 21:48
Show Gist options
  • Save madTeddy/23fcc7894f946c3e4a2d0cc99e09bacb to your computer and use it in GitHub Desktop.
Save madTeddy/23fcc7894f946c3e4a2d0cc99e09bacb to your computer and use it in GitHub Desktop.
2D Circular Movement with Jump (Unity)
using System.Collections;
using UnityEngine;
public class CircularMovement : MonoBehaviour
{
[SerializeField] private float _speed = 1f;
[SerializeField] private float _radius = 3f;
[SerializeField] private float _jumpForce = 2f;
[SerializeField] private float _gravity = 5f;
[SerializeField] private Transform _center;
private float _angle;
private float _jumpVelocity;
private bool _isJumping;
private void Update()
{
if (Input.GetMouseButtonDown(0) && !_isJumping)
{
_isJumping = true;
StartCoroutine(Jump());
}
_angle += _speed * Time.deltaTime;
Vector3 offset = new Vector3(Mathf.Sin(_angle), Mathf.Cos(_angle), 0) * (_radius - _jumpVelocity);
transform.position = _center.position + offset;
}
private IEnumerator Jump()
{
float targetVelocity = _jumpForce;
while (_isJumping)
{
float gravityPerFrame = _gravity * Time.deltaTime;
_jumpVelocity = Mathf.Lerp(_jumpVelocity, targetVelocity, gravityPerFrame);
targetVelocity -= gravityPerFrame;
if (_jumpVelocity <= 0)
break;
yield return null;
}
_jumpVelocity = 0;
_isJumping = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment