x


On Mouse Drag Game Object follows Mouse on a single Axis.

Hello People,

I'm trying to create a 2d game and the game objects should follow the mouse on a single axis (the x axis), when the user drags the object.

Here's my code, the problem is, that the game object flies out of the screen as soon as i try to drag it, instead of following the mouse,

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]

public class MovePoint : MonoBehaviour

{
    void OnMouseDrag()
    {
        Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        point.y = gameObject.transform.position.y;
        gameObject.transform.Translate(point.x,0,0);
        Screen.showCursor = false;
    }

    void OnMouseUp()
    {
        Screen.showCursor = true;
    }

}

Help would be much appreciated.

more ▼

asked Mar 10 '11 at 02:14 PM

djun9el gravatar image

djun9el
1 1 1 1

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

instead of gameObject.transform.Translate(... do a gameObject.transform.positon = point...or whatever you want to set it to.

Translate moves the object, at its current position, by some amount. You want to set the position to the position of the mouse so you can just set the position directly.

You should really cache the transform of the object in a start or awake function. check out caching in the docs.

more ▼

answered Mar 10 '11 at 03:07 PM

loopyllama gravatar image

loopyllama
1.5k 1 4 18

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1035
x983
x322
x316
x286

asked: Mar 10 '11 at 02:14 PM

Seen: 2777 times

Last Updated: Mar 10 '11 at 02:14 PM