- Home /
Question by
kannan21 · Jan 29, 2013 at 05:59 PM ·
mouse follow
How to make a cube follow my mouse pointer?
How to make a cube follow my mouse pointer where ever i move it?
Comment
Best Answer
Answer by Qvintusdk · Jan 29, 2013 at 06:16 PM
You could use RaycastHit and then transform the cube's position according to where the Raycast hits.
C# script example would be as following:
using UnityEngine;
using System.Collections;
public class RaycastMoveCube : MonoBehaviour
{
public Camera camToUse;
public Transform CubeToTransform;
// Update is called once per frame
void Update()
{
Ray ray;
RaycastHit hit;
ray = camToUse.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
CubeToTransform.transform.position = hit.point;
}
}
}
}
This script has a max range of 100 but you can change that. Example : Physics.Raycast(ray, out hit, 500.0f)
Works Perfectly for me, how would I go about setting no depth and staying at the pointer not moving on its own?
Your answer
![](https://koobas.hobune.stream/wayback/20220613091812im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[2D] Problem With Mouse Follow Object 1 Answer
Mouse Follow (Not Working) - ): 1 Answer
Mouse Look/Follow is not following first person 0 Answers
Mouse follow collider in a 2D game 0 Answers
Mouse Follow Problem 1 Answer