To move objects by clicking on them, follow these steps:
- Delete the Cube-player GameObject.
- Set the position of Main Camera to (0, 3, -5) and its rotation to (25, 0, 0).
- Create a C# script class called ClickMove:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class ClickMove : MonoBehaviour {
public float multiplier = 500f;
private Rigidbody rigidBody;
private void Awake() {
rigidBody = GetComponent<Rigidbody>();
}
void OnMouseDown() {
float x = RandomDirectionComponent();
float y = RandomDirectionComponent();
float z = RandomDirectionComponent();
Vector3 randomDirection = new Vector3(x,y,z);
rigidBody.AddForce(randomDirection);
}
private float RandomDirectionComponent() {
return (Random.value - 0.5f) * multiplier;
}
}
- Create a Cube GameObject and add an instance object of the ClickMove script class as a component.
You should see that a RigidBody component is automatically added to the new cube since...