Search Unity

  1. Calling all beginners! Join the FPS Beginners Mods Challenge until December 13.
    Dismiss Notice
  2. It's Cyber Week at the Asset Store!
    Dismiss Notice

Instantiate a prefab on touch position Raycast

Discussion in 'iOS and tvOS' started by Tapgames, Sep 7, 2011.

  1. Tapgames

    Tapgames

    Joined:
    Dec 1, 2009
    Posts:
    242
    Hi All,

    After a long search I found some code to get a prefab on the same location I touch and it works.
    My Question is, is there a way to get the prefab instantiate a few units above the point i touch?
    The prefab is a cube with a rigid body so they fall at the point I touch.

    Thank in advance!


    Code (csharp):
    1. public var newObject : GameObject;
    2.  
    3. var layerMask = 1 << 8;
    4.  
    5. function Update () {
    6.     for (var Touch : Touch in Input.touches) {
    7.         if (Touch.phase == TouchPhase.Began) {
    8.            
    9.             var ray = Camera.main.ScreenPointToRay (Touch.position);
    10.             var hit: RaycastHit;
    11.             if (Physics.Raycast (ray, hit, layerMask)) {
    12.                 Instantiate (newObject, hit.point, transform.rotation);
    13.             }
    14.         }
    15.     }
    16. }
     
  2. handsomePATT

    handsomePATT

    Joined:
    Nov 30, 2010
    Posts:
    574
    you just need to increase the y value when you instantiate.

    new Vector3(hit.point.x, hit.point.y + 10, hit.point)
     
  3. Tapgames

    Tapgames

    Joined:
    Dec 1, 2009
    Posts:
    242
    Hi handsomePATT,

    Thanks for your advice!

    I tried to put you code in my instantiate line but getting errors, i'm sure it's me that is doing it wrong ;)
    I have very very limited programming know how.
    Can you please show me how to put you code in my script?

    Thanks a lot!
     
  4. handsomePATT

    handsomePATT

    Joined:
    Nov 30, 2010
    Posts:
    574
    probably cuz mine is c#. i think javascript is the same just take out the new keyword.
     
  5. Sam_Unity

    Sam_Unity

    Joined:
    Apr 25, 2011
    Posts:
    16
    Still not working in my case when I click the object some times instantiated in the right place and some times is not, not really stable!!! any one who has tried it?
     
  6. veykys

    veykys

    Joined:
    Nov 14, 2019
    Posts:
    1
    TE AMO BOLUDO, ESTOY HACE 4 HORAS XAShdgclkfaj