Tarodev

Rolling a cube

Jul 2nd, 2021 (edited)
3,293
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.03 KB | None | 1 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class PlayerController : MonoBehaviour {
  5.     [SerializeField] private float _rollSpeed = 5;
  6.     private bool _isMoving;
  7.  
  8.     private void Update() {
  9.         if (_isMoving) return;
  10.  
  11.         if (Input.GetKey(KeyCode.A)) Assemble(Vector3.left);
  12.         else if (Input.GetKey(KeyCode.D)) Assemble(Vector3.right);
  13.         else if (Input.GetKey(KeyCode.W)) Assemble(Vector3.forward);
  14.         else if (Input.GetKey(KeyCode.S)) Assemble(Vector3.back);
  15.  
  16.         void Assemble(Vector3 dir) {
  17.             var anchor = transform.position + (Vector3.down + dir) * 0.5f;
  18.             var axis = Vector3.Cross(Vector3.up, dir);
  19.             StartCoroutine(Roll(anchor, axis));
  20.         }
  21.     }
  22.  
  23.     private IEnumerator Roll(Vector3 anchor, Vector3 axis) {
  24.         _isMoving = true;
  25.         for (var i = 0; i < 90 / _rollSpeed; i++) {
  26.             transform.RotateAround(anchor, axis, _rollSpeed);
  27.             yield return new WaitForSeconds(0.01f);
  28.         }
  29.         _isMoving = false;
  30.     }
  31. }
Add Comment
Please, Sign In to add comment