- Home /
How to control an object with a mouse?
Well, I've been trying to work with this code that I got from elsewhere.
pragma strict
var myCamera : Camera; function Start () {
}
function Update () {
var vec : Vector3 = myCamera.ScreenToWorldPoint(Input.mousePosition);
var side : float = 933.6987;
var top : float = 28.25993;
vec.x = Mathf.Clamp(vec.x, -side, side);
vec.y = Mathf.Clamp(vec.y, -top, top);
vec.z = 843.3414;
transform.position = vec;
}
Basically the values in the code are the position values of the object I'm trying to move. As of now my object can only move along the X axis and it's movement is also limited as though there are invisible walls. Any help appreciated. Thanks in advance.
Answer by Jamora · Aug 01, 2013 at 07:24 AM
You need to consider on which plane you are moving your characters. Then set the values accordingly. Based on your code, I'm assuming it's a 2D plane; possibly XZ, because you say you cannot move vertically.
The reason you cannot move vertically is that you set vec.z to a constant; try vec.z = Mathf.Clamp(vec.y, -top, top);
instead. If you need your objects to be on the same y plane, set vec.y = 0;
The reason there are 'invisible walls' is because you're clamping the x value. Clamping means that the value is set between the given min and max values, which in your case is between -933.6987 and 933.6987. Remove the clamp, or set it to appropriate values and you should be all set.
Your answer
![](https://koobas.hobune.stream/wayback/20220613111328im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Huh click and go script working 50% 0 Answers
Drag object along Z axis using mouse 1 Answer
Move to mouse position 1 Answer