Hi, I am trying to write code that will add force to a gameobject when the player touches them on the screen.
I have tried with the following code but it just doesn’t work at all when I build and run on my phone. I cant for the life of me see the error in my code here, so perhaps someone could point out where I have gone wrong?
Basically, nothing happens when you touch the object, it just falls.
Here is the code I am using:
public float forceUpMin;
public float forceUpMax;
public float forceSideMin;
public float forceSideMax;
public float spinMin;
public float spinMax;
Vector3 force;
float forceX;
float forceY;
float forceZ = 0.0f;
Vector3 randomTorque;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray, out hit))
{
if(hit.collider.tag == "Can")
{
ShootCan(hit.collider.gameObject);
}
}
}
}
if(lives == 0)
{
GameOver();
}
}
public void ShootCan(GameObject go)
{
forceX = Random.Range(forceSideMin, forceSideMax);
forceY = Random.Range(forceUpMin, forceUpMax);
force.x = forceX;
force.y = forceY;
force.z = forceZ;
randomTorque.x = Random.Range(-spinMin, spinMax);
randomTorque.y = Random.Range(-spinMin, spinMax);
randomTorque.z = Random.Range(-spinMin, spinMax);
go.GetComponent<ConstantForce>().torque = randomTorque;
go.GetComponent<Rigidbody>().AddForce(force);
}