- Home /
How can i make the object follow mouse position
I want to make an object move in world using mouse position input, here is the code:
IEnumerator ThrowTrap(){
Throwing = true;
GameObject t = Instantiate (trap, transform.position + offset, Quaternion.identity);
Camera c = Camera.main;
Event e = Event.current;
Vector2 mousePos = new Vector2 ();
mousePos.x = e.mousePosition.x;
mousePos.y = c.pixelHeight - e.mousePosition.y;
Vector3 p = c.ScreenToWorldPoint(new Vector3(mousePos.x,mousePos.y,c.nearClipPlane));
t.transform.Translate(p);
yield return new WaitForSeconds (trapDuration);
Destroy (t.gameObject);
yield return new WaitForSeconds (trapCooldown);
Throwing = false;
}
Answer by Topthink · Jun 19, 2018 at 08:47 PM
Have a look at this link and perhaps this code. It's not super clear what you are trying to accomplish or trying to get to move. https://docs.unity3d.com/Manual/nav-MoveToClickPoint.html
// MoveToClickPoint.cs
using UnityEngine;
using UnityEngine.AI;
public class MoveToClickPoint : MonoBehaviour {
NavMeshAgent agent;
void Start() {
agent = GetComponent<NavMeshAgent>();
}
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {
agent.destination = hit.point;
}
}
}
}
I hope that helps to some extent or that at least it points you in the right direction. Best wishes.
Sorry, ive explanied myself wrong. What i want is to throw a projectile from the player in the direction of the mouse, something like skillshots in league of legends.
What about something like this:
using UnityEngine;
using System.Collections;
public class Shooter : $$anonymous$$onoBehaviour
{
public Rigidbody projectile;
public Transform shotPos;
public float shotForce = 1000f;
public float moveSpeed = 10f;
void Update ()
{
float h = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate(new Vector3(h, v, 0f));
if(Input.GetButtonUp("Fire1"))
{
Rigidbody shot = Instantiate(projectile, shotPos.position, shotPos.rotation) as Rigidbody;
shot.AddForce(shotPos.forward * shotForce);
}
}
}
I know it's not exactly what you are referring to but "shooting" in a particular direction isn't too far removed from "throwing" something in a particular direction.
Your answer
![](https://koobas.hobune.stream/wayback/20220612165104im_/https://answers.unity.com/themes/thub/images/avi.jpg)