Hi hows it going,
I have not been using Unity for over a year and I finally decided to come back and do some work.
I have been working on a Geometry Dash-esque game and I was trying to find a way to rotate the cube mid air when the character jumps OR goes off of a ledge. I was trying to think about a solution to this and I thought maybe if I calculated the trajectory and did some maths based off of gravity as to where the character will land and rotated the character a certain amount of times based on how long it would take to get there.
Basically, I want the character which is a cube, to rotate to land on a side perfectly each time it goes of a ledge or jumps.
Here is my movement code:
public Rigidbody rigidBody;
public float moveSpeed = 5f;
public float jumpForce = 2f;
public float jumpForceMultiplier = 30f;
public float jumpDelay = 1;
public bool canJump = true;
Collider thisCollider;
public GameObject groundCheck;
bool jump = false;
// Use this for initialization
void Start () {
rigidBody = gameObject.GetComponent<Rigidbody>();
thisCollider = gameObject.GetComponent<Collider>();
}
// Update is called once per frame
void Update () {
canJump = GroundCheck();
if(jump == false && canJump ){
jump = Input.GetKeyDown(KeyCode.Space);
}
}
void FixedUpdate () {
if(jump){
rigidBody.velocity = new Vector3(rigidBody.velocity.x,jumpForce*jumpForceMultiplier,moveSpeed);
StartCoroutine(freezeRotation());
jump = false;
}else{
rigidBody.velocity = new Vector3(rigidBody.velocity.x,rigidBody.velocity.y,moveSpeed);
}
}
bool GroundCheck(){
return Physics.Raycast(transform.position, -Vector3.up, thisCollider.bounds.extents.y + 0.1f);
}
IEnumerator freezeRotation(){
rigidBody.constraints = RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
rigidBody.AddTorque(20f,0,0);
yield return new WaitForSeconds(0.1f);
yield return new WaitUntil(GroundCheck);
rigidBody.constraints = RigidbodyConstraints.FreezeRotation;
yield break;
}
}
Cheers!