NaZer
November 12, 2012, 8:24pm
1
Ok so im trying to make an object that is controlled by the mouse but is limited to a circle. the purple dot is the object and as you can se it still needs to move even though the mouse exits the circle (the mouse should not be visible in-game) And also the whole thing needs to be a child of another object so it moves relative to its parents position. But so far ive had no luck at achieving this.
[4897-unity+problem+2.jpg|4897]
I hope you understood my problem and are able to help me
Thank you
It depends a lot on what you’re using to move your purple dot, but after the move happens you can constrain it within the circle.
(This is pseudocode - rewriting in js or csharp up to you.)
In world space:
if( Vector3.Distance( position, origin ) > maxDistance )
newPosition = (position-origin).normalized * maxDistance + origin;
Or, if your purple dot is parented to the center, might look something like this:
if( position.magnitude > maxDistance )
newPosition = position.normalized * maxDistance;
(Also, I recommend boning up on your vector math if you’re going to be making a 2D game - time spent now will save you time later.)
Scribe
November 12, 2012, 9:13pm
3
I wrote this:
var Parent : Transform;
var Obj : Transform;
var Radius = 5;
var Dist : float;
var MousePos : Vector3;
var ScreenMouse : Vector3;
var MouseOffset : Vector3;
function Update() {
MousePos = Input.mousePosition;
ScreenMouse = camera.main.ScreenToWorldPoint(Vector3(MousePos.x, MousePos.y, Obj.position.z-camera.main.transform.position.z));
MouseOffset = ScreenMouse - Parent.position;
Obj.position.x = ScreenMouse.x;
Obj.position.y = ScreenMouse.y;
Dist = Vector2.Distance(Vector2(Obj.position.x, Obj.position.y), Vector2(Parent.position.x, Parent.position.y));
if(Dist > Radius){
var norm = MouseOffset.normalized;
Obj.position.x = norm.x*Radius + Parent.position.x;
Obj.position.y = norm.y*Radius + Parent.position.y;
}
}
However Jamie suggested much the same thing and got in there first! Others might find this useful in the future however so I thought I’d share it.
Also might help if you can’t work out how to utilise Jamie’s code.
Scribe