What is the best method of creating an element in a 3D environment along a specific axis?
I have a 3D space. When a user clicks their mouse I want to drop an item at a fixed Y and Z coordinate, but a variable X coordinate, relative to where the user clicked.
Please see the following image.
When the user clicks I want to drop a block onto the seesaw shape from a fixed height.
I can achieve this by creating a transparent plane in front of the seesaw and firing a ray cast at it, this will give me a good X coordinate to place on. The Y and Z coordinates are hard-coded, so aren't an issue (I want it to always fall from the same height). However, it seems like a very inefficient way to do something quite simple.
What is the best method of achieving this?
Below is my code that works using a ray cast. I don't have a transparent plane in the foreground, so it only works if I click on the actual seesaw. Clicking anything else makes the ray collide with trees in the background, which gives me coordinates that are way off.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class clickBehaviour : MonoBehaviour
{
public GameObject GameCube;
Ray ray;
RaycastHit hit;
// Update is called once per frame
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (Input.GetButtonDown("Fire1"))
{
GameObject obj = Instantiate(GameCube, new Vector3(-75, 9, hit.point.z), Quaternion.identity) as GameObject;
Debug.Log(hit.point);
}
}
}
}
In this scene the Z axis is left to right.
Your answer
Follow this Question
Related Questions
Detecting Rays from controller input and cast from Object 0 Answers
How can I get a two-dimensional blend tree to match direction and rotation? 0 Answers
How do i calculate the outer bounds??? 0 Answers
Calculate normal vector to the plane that was hit by raycast 1 Answer
mechanics from Sky Force of shooting 0 Answers