I’m pretty new to unity and I wanted a GameObject to follow my cursor.
I don’t want it to be on the mouse cursor but move towards it at a certain speed.
Does somebody have this kind of script and wants to share it?
Thanks in advance;)
I’m pretty new to unity and I wanted a GameObject to follow my cursor.
I don’t want it to be on the mouse cursor but move towards it at a certain speed.
Does somebody have this kind of script and wants to share it?
Thanks in advance;)
This very much depends on your settings. Do you have a terrain, is it 2D or 3D? Do you use physics to move the object or just plain changes in script(force or no force)?
What you Probably want to do is use some raycasting with your mouse as origin and cast that against like the terrain. This will give you the point in 3D space where the cursor “is”. Then you need to take your object, say Object A and set it to move towards MousePos. This is simply a vector3: MousePos-PositionOfObjectA and then apply the transformation. Please provide us with your attempt as well, we dont want to do the work for you.
Raycasting and Vector3.Lerp is what you need to look at.
This is my script.
Its a mess and it doesn’t work.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
public void AddObject(int index{
var typeofbuilding = buildingTypes[index];
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 1000))
{
Instantiate(typeofbuilding, hit.point, Quaternion.identity);
MoveObject(typeofbuilding);
return;
}
}
//move the selected object around
public void MoveObject(GameObject movingBuilding)
{
//Any object passed to this function should follow the mouse around
var canmove = true; //as long as this value is true, loop through the function
if(canmove == true)
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 1000))
{
if(Input.GetButtonDown(“LMB”))
{
movingBuilding = null; //release the gameobject from the movingobject variable
canmove = false;
}
else
{
movingBuilding.transform.position = hit.point; //as long as the left mouse button isnt pushed follow the mouse cursor
}
}
}
}
}
You need to break up your code and do it step wise.
Throwing all togheter from different scripts usualy don’t work.
There are several errors in your script.
Start by instantiating your buildings with the mouse button.
Once thats working you can look for a way to move an object towards a raycast point.