Question by
Hawknasty13 · Oct 01, 2018 at 06:19 PM ·
mousepositionthrowing
How do I throw an object toward mouse cursor in 3D?
I am making a 3d side-scroller where the player can throw instantiated snowballs. Right now I have it so the player can throw the snowballs "forward", but I have decided that throwing the snowballs where the mouse click is will be better for the game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowSnowball : MonoBehaviour {
public GameObject Snowball;
private Transform myTransform;
public float propelForce = 30f;
private Vector3 MousePos;
// Use this for initialization
void Start ()
{
SetInitialReferences();
}
// Update is called once per frame
void Update () {
{
Vector3 MousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y,0);
MousePos = Camera.main.ScreenToWorldPoint(MousePos);
}
{
if (Input.GetButtonDown("Fire1"))
{
throwSnowball();
}
}
void SetInitialReferences()
{
myTransform = transform;
}
void throwSnowball() //instantiate snowball. myTransform is player location and TransformPoint is in front of player using vector.
{
GameObject go = (GameObject) Instantiate(Snowball, myTransform.TransformPoint(0f, 0, 0), myTransform.rotation);
go.GetComponent<Rigidbody>().AddForce(myTransform.forward * propelForce, ForceMode.Impulse);
Destroy(go, 5);
}
}
I want to make the player throw the snowball where the MousePos is.
AddForce.myTransform.FORWARD <-- need that to be MousePos, but apparently that is not allowed.
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612175559im_/https://answers.unity.com/themes/thub/images/avi.jpg)