I’m using some code from another answer thread about how to rotate a cube which seems pretty efficient as far as the code goes although the actual code is in JavaScript and I work in C#. I’m actually looking for the most efficient way to edit this script in order to rotate an extruded cube.
The problem is that the script works well with a normal cube but rotates on at its center then falls down with an extruded cube. What would be the best possible way to rotate the extruded cube on its pivot point instead of its center point?
Here is the script Im currently using:
var speed: float = 2.5; // flops per second
var size: float = 1; // block size
var flopping = false;
function Update(){
var move = Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (move.magnitude > 0.2) Flop(move);
}
function Flop(movDir: Vector2){
var pivot: Vector3;
var dir: Vector3;
if (flopping) return; // ignore other commands while flopping
flopping = true; // signals it's flopping
if (movDir.y > 0){ // move forward?
dir = Vector3.forward; // will flop forward
pivot = Vector3(0,-1,1); // defines point around which rotate
}
else
if (movDir.y < 0){
dir = -Vector3.forward;
pivot = Vector3(0,-1,-1);
}
else
if (movDir.x < 0){
dir = -Vector3.right;
pivot = Vector3(-1,-1,0);
}
else
if (movDir.x > 0){
dir = Vector3.right;
pivot = Vector3(1,-1,0);
}
AlignBlock(); // aligns block to grid before flopping
// calculates the point around which the block will flop
pivot = transform.position + (pivot * size / 2);
var org = transform.position - pivot;
var dest = (transform.position + dir * size) - pivot;
var rot0 = transform.rotation;
var rot1 = Quaternion.FromToRotation(org, dest) * rot0;
var a: float = 0;
while (a < 1){
var dt = Time.deltaTime * speed;
a += dt;
transform.position = Vector3.Slerp(org, dest, a) + pivot;
transform.rotation = Quaternion.Lerp(rot0, rot1, a);
yield;
}
if (audio) audio.Play(); // makes the flop sound
flopping = false;
}
private function AlignBlock(){
var angles = transform.eulerAngles;
// forces euler angles to be multiple of 90
angles.x = 90 * Mathf.RoundToInt(angles.x / 90);
angles.y = 90 * Mathf.RoundToInt(angles.y / 90);
angles.z = 90 * Mathf.RoundToInt(angles.z / 90);
transform.eulerAngles = angles;
var pos = transform.position;
// forces x and z to be in a grid
pos.x = size * Mathf.RoundToInt(pos.x / size);
pos.z = size * Mathf.RoundToInt(pos.z / size);
if (!rigidbody) pos.y = size * Mathf.RoundToInt(pos.y / size);
transform.position = pos;
}