First, the basic knowledge point 1, coordinates, vectors, etc.
if(Input.getmousebuttondown (0)) { //1. Convert mouse coordinates to world coordinates because the mouse Z axis may not exist, it is customized to 3Vector3 Targetpos = Camera.main.ScreenToWorldPoint (NewVector3 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y,3)); //2, each gameobject has transform.position position. //3, vector v2-v1 means v1 point to v2 vectorVector3 dir = targetpos-Camera.main.transform.position; //4. Add a force This.gameobject.getcomponent<rigidbody> (). Addforce (dir*3, Forcemode.impulse); }
2. Dynamic creation of Game objects
//left mouse button click if(Input.getmousebuttondown (0) {gameobject gonew=gameobject.createprimitive (Primitivetype.cube); GoNew.transform.position=NewVector3 (3,3,0); Gonew.addcomponent<Rigidbody>(); Gonew.name="TestCube"; Go. Getcomponent<renderer> (). Material.color = color.red; }
Create Game object: Gameobject.createprimitive (Primitivetype.cube)
Add Game Object Component:gonew.addcomponent<rigidbody> ();
Rigidbody, scripts, and all components under the component menu
3. Destroying objects
Gameobject GoS = Gameobject.find ("TestCube");
Destroy (GoS, 2);
Second, example-hit the box
1. Create a new project
2, increase the ground
3. Add a C # script
Automatic destruction of autodestory scripts
Public class autodestory:monobehaviour{ // use of this for initialization void Start () { } // Update is called once per frame void Update () { } void onbecameinvisible () { Destroy (this . gameobject);} }
View Code
Initializing the Init.cs script
Public classInit:monobehaviour {//Use this for initialization voidStart () { for(inti =0; I <4; i++) { for(intj =0; J <4; J + +) {Gameobject go=gameobject.createprimitive (Primitivetype.cube); Go.transform.position=NewVector3 (I, J,-1); if(J%2==0) {go. Getcomponent<Renderer> (). Material.color =color.red; } go. AddComponent<Rigidbody>(); Go. AddComponent<AutoDestory>(); } } } //Update is called once per frame voidUpdate () {if(Input.getmousebuttondown (0) {gameobject gonew=gameobject.createprimitive (Primitivetype.sphere); GoNew.transform.position=Camera.main.transform.position; Gonew.addcomponent<Rigidbody>(); Gonew.addcomponent<AutoDestory>(); Vector3 Targetpos= Camera.main.ScreenToWorldPoint (NewVector3 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y,3)); Gonew.getcomponent<Rigidbody> (). Addforce ((targetpos-camera.main.transform.position) *Ten, Forcemode.impulse); } }}
View Code
Interface effect
Hit the box effect
003-unity3d Physics Engine-Example 2 dozen boxes