Tuesday, 22 September 2015

Instantiate Prefab apply AddForce unity 2d c#

About Components (How to):-



  1. Create a new project with 2D mode as shown below image.
  2. First Create Empty Game Object and rename it 'ArrowImage' at Hierarchy.
  3. Add Component 'Sprite Renderer' at Inspector
  4. Import arrow image from your Window/Mac Desktop at project folder and drop it to sprite field.
  5. Add Component 'Rigidbody 2D' at inspector of your arrow.
  6. Save Scene and drop 'Arrow Object' to Project folderNow it's convert into a prefab.
  7. Delete your 'ArrowImage' at Hierarchy
  8. Create Spawn point (where you want to release your arrow.. Probably from bow ) 
  9. Add Component 'bolow script (InstantiateScript)' to spawnPoint.
  10. Browse ArrowImage Prefab for InstantiateScript.
  11. Play your scene... Click on you Game View.

About Script Tips:-


1. You should use LateUpdate(){} for physics iterations.


Script : -



using UnityEngine;
using System.Collections;

public class InstantiateScript : MonoBehaviour {

    public Rigidbody2D arrow1;
    public int Force = 9000;

    void LateUpdate () {
        if (Input.GetButtonDown("Fire1")) {
            
            Rigidbody2D arrowRig2D;
            arrowRig2D = Instantiate(arrow1transform.positiontransform.rotationas Rigidbody2D;
            arrowRig2D.AddForce(-transform.right * Force * Time.deltaTime);
        }

    }
}



if you want to decrease image size at unity... you should increase Pixel Per Unit image import Settings as shown below image



No comments:

Post a Comment