- Home /
Trying to instantiate a ball at the cursor position
I've looked at various topics on this, and it seems that what I've got should work.
So I only want the ball to instantiate on the x axis of the mouse cursor. The other two axis are fixed. At the moment, no matter where I click, the ball spawns in the exact same position, even on the x axis, and below the camera. Hoping someone can tell me where I've gone wrong. Thanks.
public class Ball : MonoBehaviour
{
[SerializeField] Camera mainCamera;
[SerializeField] GameObject ball;
Vector3 mousePosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
mousePosition = Input.mousePosition;
mousePosition.y = 3.6f;
mousePosition.z = 0f;
var ballPos = mainCamera.ScreenToWorldPoint(mousePosition);
if (Input.GetMouseButtonDown(0))
{
Instantiate(ball, ballPos, Quaternion.identity);
}
}
}
Answer by mchts · May 08, 2019 at 07:23 AM
Here is the edited version of your code:
using UnityEngine;
public class Ball : MonoBehaviour {
[SerializeField] Camera mainCamera;
[SerializeField] GameObject ball;
public float offset; //this is the distance you want to add to z axis of your camera position
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(0)) {
Vector3 ballPosition = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mainCamera.transform.position.z + offset));
ballPosition.y = 3.6f;
Instantiate(ball, ballPosition, Quaternion.identity);
}
}
}
Your answer
Follow this Question
Related Questions
Camera ScreenToWorldPoint Instatiating 1 Answer
Projectiles trigger affecting other projectiles of same prefab - C# 0 Answers
Instanciate prefab responsively 1 Answer
Can't convert from mouse screen position to world position 3 Answers
Show GUI Texture on Trigger and Instantiate Object if Button pressed while In Trigger? 1 Answer