Reputation: 113
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody rb;
public float f = 100;
public float b = -100;
public float l = -100;
public float r = 100;
public float u = 10;
public bool onGround = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (onGround)
{
if (Input.GetKeyDown("space"))
{
rb.AddForce(0, u, 0, ForceMode.VelocityChange);
onGround = false;
}
}
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, f);
}
if (Input.GetKey("a"))
{
rb.AddForce(l, 0, 0);
}
if (Input.GetKey("d"))
{
rb.AddForce(r, 0, 0);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, b);
}
if(onGround == false)
{
rb.AddForce(Physics.gravity * rb.mass);
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.tag == "Ground")
{
onGround = true;
}
}
}
This is my code. Since I wanted my cube to topple while moving, I would like to add forces above center of mass with a slight delay. According to how I visualize, this will make the cube topple.
How could I do this, Is this a good way of doing this or there is another way to topple my cube? Thanks.
Upvotes: 1
Views: 58
Reputation: 120
you can do it in unity directly by adding physical material to the cube in it's (Box Collider) and changing the values, but if you want to do it from code you have to mention it first and then edit its values like this:
using UnityEngine;
public class TestPlayerMovement : MonoBehaviour {
public BoxCollider BX;
// and then drag it from unity
void FixedUpdate () {
//it's better to use FixedUpdate bec it's movement
//examples
BX.material.bounciness = 0;
BX.material.dynamicFriction = 0;
BX.material.staticFriction = 0;
print (BX.material.staticFriction);
print (BX.material.bounciness);
print (BX.material.dynamicFriction);
}
Upvotes: 1