Search Unity

  1. Read here for Unity's latest plans on OpenXR.
    Dismiss Notice

Help Wanted How can I spawn an object in front of the camera unless the position and direction of the device?

Discussion in 'AR' started by realmcrafter, Dec 7, 2020.

  1. realmcrafter

    realmcrafter

    Joined:
    Nov 12, 2020
    Posts:
    7
    I'm creating a game where the player can swipe a ball to whatever direction. The problem I encounter is that when the ball is spawned the first time all the other balls that are spawned, will load on the same position as the first ball whatever direction I'm aiming at with my camera.

    I want it to get it always spawned in front of the camera no matter the location, position and direction of my phone's camera.

    I tried using tags to get the location of the camera en the cup of where the ball need to get thrown in but still the ball doesn't get loaded in front of the camera no matter the location. I guess this is not the right way to achieve this and I was wondering what is?

    The code I'm using for spawning the ball on a certain location

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SpawnBall : MonoBehaviour
    6. {
    7.  
    8.     [SerializeField]
    9.     GameObject ball;
    10.  
    11.     public float distanceX;
    12.     public float distanceY;
    13.     public float distanceZ;
    14.  
    15.     public float ballX;
    16.     public float ballY;
    17.     public float ballZ;
    18.  
    19.     public void Spawn()
    20.     {
    21.         distanceX = GameObject.FindGameObjectWithTag("Cup").transform.position.x - GameObject.FindGameObjectWithTag("MainCamera").transform.position.x;
    22.         distanceY = GameObject.FindGameObjectWithTag("Cup").transform.position.y - GameObject.FindGameObjectWithTag("MainCamera").transform.position.y;
    23.         distanceZ = GameObject.FindGameObjectWithTag("Cup").transform.position.z - GameObject.FindGameObjectWithTag("MainCamera").transform.position.z;
    24.  
    25.         ballX = distanceX / 4;
    26.         ballY = distanceY / 4;
    27.         ballZ = distanceZ / 4;
    28.  
    29.         Instantiate(ball, new Vector3(ballX, ballY, 10f), Quaternion.identity);
    30.     }
    31. }
     
unityunity