Moving an object by touch->drag?

Hi all

I’m new to scripting. I have my game object runs from A to B (along the X axis) and then return from B to A. I’m wondering how can i move it by touching and then drag it (still along X axis), after that, it continues to run.

Any suggestion or tutorial about this?

Thank you.

help!!!

Send me a pm to remind me in 24-48 hours. I may have something back on my main machine…

Ok… ^^ Thank you in advance :smile:

to begin with, apply force to the rigidbody of the object to make it move

then make that object always look at its destination

since its a rigidbody now, any other force pushing against it will make it move, but it will always be looking at, and moving towards
point A or B

as far as dragging it, im not sure.

it could go something like, when its requested that its being pulled, its new destination is toward what you are pulling with and NOT A or B but point C (the point that the you want the object to go towards temporarily)

Here is the code from Unity 2D tutorial, i attached this to game object, set point A and B to make the object move:

var targetA : GameObject;
var targetB : GameObject;

var speed : float = 0.1;

function FixedUpdate () {
	var weight = Mathf.Cos(Time.time * speed * 2 * Mathf.PI) * 0.5 + 0.5;
	transform.position = targetA.transform.position * weight
						+ targetB.transform.position * (1-weight);
}

And i found this scipt in Unity manual:

// Moves object according to finger movement on the screen

var speed : float = 0.1;
function Update () {
if (Input.touchCount > 0 
Input.GetTouch(0).phase == TouchPhase.Moved) {

// Get movement of the finger since last frame
var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;

// Move object across XY plane
transform.Translate (-touchDeltaPosition.x * speed,
-touchDeltaPosition.y * speed, 0);
}
}

I did apply the script to the moving object but when i touched and dragged it, it didn’t seem to move, it just continued to go from A ↔ B. How can i detect whether the object is going from A to B or from B to A, drag the object and set the point is C, then let it go from there to the destination?

Thanks

I see, youre trying to use the touch feature. I had a different idea of what you wanted.

So basically, if you apply the finger movement script to the object, it moves like you want it to move.

If you ALSO apply the other script, it wants to just move from point A to point B correct?

Well, you have the answer right in front of you. When you’re touching the screen, disable the move by doing this:

Insert this line here

if (Input.touchCount = 0)

right here

var targetA : GameObject;
var targetB : GameObject;

var speed : float = 0.1;

function FixedUpdate () {
[COLOR="red"]if (Input.touchCount == 0){[/COLOR]
	var weight = Mathf.Cos(Time.time * speed * 2 * Mathf.PI) * 0.5 + 0.5;
	transform.position = targetA.transform.position * weight
						+ targetB.transform.position * (1-weight);
[COLOR="red"]}[/COLOR]
}

that should disable its back and forth movement while youre touching the screen.

Thanks for helping me :smile:

However, the game doesn’t work well on my Android phone. I touch the moving game object and i can make it stop but i can’t move it. Sorry for my sill question, but does my touch code above do what i describe? Will it allow me to drag the game object?

Another problem is: the game object still seems to move (in the background), when i release my finger, it doesn’t continue to go from that point, but somewhere else from A ↔ B. :frowning:

Any suggestion?

This was a Unity-iPhone v1.7 (or earlier) script:

var object : GameObject;

function Update () {
 
    for (var touch : iPhoneTouch in iPhoneInput.touches){
        var ray = Camera.main.ScreenPointToRay(touch.position);
        var hit : RaycastHit;
        if (Physics.Raycast (ray, hit, 100)) {
            if(touch.phase == iPhoneTouchPhase.Began || touch.phase == iPhoneTouchPhase.Moved) {
                var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
                object.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, cameraTransform.z - 0.5));
            }
        }
    }
  
}

Give this a go and see what you get.

Here’s two threads I know of:

ps: I’ve not looked closely at any of this in a while, so it might be worth combing thru before you use… also try a search for “dragging” or something like that in iOS.

As i want to port my 2D game to Android, i modified some lines of your code, but it doesn’t work well because when i touch and move an object, other objects are moved too.

I’m editing this script:

private var object : Transform;       
private var offSet : Vector3;

function Update ()
    for (var touch : Touch in Input.touches)
    {
    var ray = camera.ScreenPointToRay(touch.position);       
    if (Input.touchCount > 0
Input.GetTouch(0).phase == TouchPhase.Moved) {       
        if (!object) {       
            var hit : RaycastHit;
            if (Physics.Raycast(ray, hit, Mathf.Infinity)) {       
                object = hit.transform;       
                offSet = object.position-ray.origin;       
            }
        }
    }
    else if (Input.touchCount > 0
Input.GetTouch(0).phase == TouchPhase.Moved) {
        object = null;       
    }
    if (object) {
        object.position = Vector3(ray.origin.x+offSet.x, object.position.y, ray.origin.z+offSet.z);       
    }
    }
}

This script does what i need. That is to move a game object a long the X axis when i touch and drag it, but when i move that object, other objects are moved too! What’s wrong in that script?? Please help!!

Anyone??

I’m not familiar with android… what changes did you make?

I see that you updated:
for (var touch : iPhoneTouch in iPhoneInput.touches){

to
for (var touch : Touch in Input.touches){

What other modifications did you do?

var object : GameObject;

function Update () {
   
	for (var touch : Touch in Input.touches){
		var ray = Camera.main.ScreenPointToRay(touch.position);
		var hit : RaycastHit;
		if (Physics.Raycast (ray, hit, 100)) {
			if(Input.touchCount > 0 
Input.GetTouch(0).phase == TouchPhase.Moved) {
				var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
				object.transform.position = Camera.main.ScreenToWorldPoint(new Vector2 (touch.position.x, 0));
			}
		}
	}
	
}

Here is my modified code. I only want the object to move long the X axis so i modified the script like that. Is there anything wrong here?

I attached the code to one object but it didn’t work. I attached it to the camera, it worked, but when i move one object, other objects are moved too. Any way to move only one object?

Thanks :slight_smile:

How are you setting your “object”?

var object : GameObject; sets the object to move. Are you assigning “object” in the inspector? Do you get any errors in the console?

I did set the game object when i attach the script to camera and i didn’t get any error :expressionless:

However, i managed to get it work with these codes:

#pragma strict
// Attach this script to an orthographic camera.
private var object : Transform;		// The object we will move.
private var offSet : Vector3;		// The object's position relative to the mouse position.

function Update () {
	var ray = camera.ScreenPointToRay(Input.mousePosition);		// Gets the mouse position in the form of a ray.
	if (Input.GetButtonDown("Fire1")) {		// If we click the mouse...
		if (!object) {		// And we are not currently moving an object...
			var hit : RaycastHit;
			if (Physics.Raycast(ray, hit, Mathf.Infinity)) {		// Then see if an object is beneath us using raycasting.
				object = hit.transform;		// If we hit an object then hold on to the object.
				offSet = object.position-ray.origin;		// This is so when you click on an object its center does not align with mouse position.
			}
		}
	}
	else if (Input.GetButtonUp("Fire1")) {
		object = null;		// Let go of the object.
	}
	if (object) {
		object.position = Vector3(ray.origin.x+offSet.x, object.position.y, ray.origin.z+offSet.z);		// Only move the object on a 2D plane.
	}
}

I didn’t know that Input.GetbuttonUp can be used on Android :expressionless:

So, i got my first problem solved. My 2nd mentioned problem is that i have an object moving from A to B and return from B to A using this code:

var targetA : GameObject;
var targetB : GameObject;

var speed : float = 0.1;

function FixedUpdate () {
	var weight = Mathf.Cos(Time.time * speed * 2 * Mathf.PI) * 0.5 + 0.5;
	transform.position = targetA.transform.position * weight
						+ targetB.transform.position * (1-weight);
}

Now, when i touch and drag the object to somewhere (C) between A and B, i want it to move from C back to A or B and then continue to move between A and B. How can i do that?

bump…

Kalos: I’ve lost track of this thread, sorry. But I assume that you’ve solved you problem?

Krodil: Do you have a specific issue?

Yeah, and hello :slight_smile:
First of all I am trying to figure out how ‘touch’ works on android/Unity.
Basically I wish to move objects around on my Xoom, and have tried some approaches so far.
I found this solution in the reference:

// Moves object according to finger movement on the screen

var speed : float = 0.1;
function Update () {
if (Input.touchCount > 0 
Input.GetTouch(0).phase == TouchPhase.Moved) {

// Get movement of the finger since last frame
var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;

// Move object across XY plane
transform.Translate (-touchDeltaPosition.x * speed,
-touchDeltaPosition.y * speed, 0);
}
}

This lets me move the object I attach the script to, but when I i.e. move down the object moves in different direction.

So I tried looking into this script I found here http://forum.unity3d.com/threads/52160-How-to-drag-an-object?highlight=drag+object and I also posted a reply quite similar to this post.
As I say in this post I think it could work out with Andeee’s script, but have difficulties modifying it.
The code is here:

var normalCollisionCount = 1;

var moveLimit = .5;
var collisionMoveFactor = .01;
var addHeightWhenClicked = 0.0;
var freezeRotationOnDrag = true;
var cam : Camera;
private var myRigidbody : Rigidbody;
private var myTransform : Transform;
private var canMove = false;
private var yPos : float;
private var gravitySetting : boolean;
private var freezeRotationSetting : boolean;
private var sqrMoveLimit : float;
private var collisionCount = 0;
private var camTransform : Transform;

function Start () {
    myRigidbody = rigidbody;
    myTransform = transform;
    if (!cam) {
        cam = Camera.main;
    }
    if (!cam) {
        Debug.LogError("Can't find camera tagged MainCamera");
        return;
    }
    camTransform = cam.transform;
    sqrMoveLimit = moveLimit * moveLimit;   // Since we're using sqrMagnitude, which is faster than magnitude
}

function OnMouseDown () {
    canMove = true;
    myTransform.Translate(Vector3.up*addHeightWhenClicked);
    gravitySetting = myRigidbody.useGravity;
    freezeRotationSetting = myRigidbody.freezeRotation;
    myRigidbody.useGravity = false;
    myRigidbody.freezeRotation = freezeRotationOnDrag;
    yPos = myTransform.position.y;
}

function OnMouseUp () {
    canMove = false;
    myRigidbody.useGravity = gravitySetting;
    myRigidbody.freezeRotation = freezeRotationSetting;
    if (!myRigidbody.useGravity) {
        myTransform.position.y = yPos-addHeightWhenClicked;
    }
}

function OnCollisionEnter () {
    collisionCount++;
}

function OnCollisionExit () {
    collisionCount--;
}

function FixedUpdate () {
    if (!canMove) return;
   
    myRigidbody.velocity = Vector3.zero;
    myRigidbody.angularVelocity = Vector3.zero;
    myTransform.position.y = yPos;
    var mousePos = Input.TouchPosition;
    var move = cam.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, camTransform.position.y - myTransform.position.y)) - myTransform.position;
    move.y = 0.0;
    if (collisionCount > normalCollisionCount) {
        move = move.normalized*collisionMoveFactor;
    }
    else if (move.sqrMagnitude > sqrMoveLimit) {
        move = move.normalized*moveLimit;
    }
   
    myRigidbody.MovePosition(myRigidbody.position + move);
}

@script RequireComponent(Rigidbody)

Any tips for me?

Krodil: Are you just testing touch moves? (I wish someone would send me an Android phone, so I could test to that platform…) I can only assume that the generic touch code works either identically or similarly on iOS Android.

Can you tell me exactly what you are trying to do?

The code I posted works fine in iOS for attaching an object to the finger and dragging it where the finger lets go.

Here’s the code updated to U3.x:

var object : GameObject;

function Update () {
   
	for (var touch : Touch in Input.touches){
		var ray = Camera.main.ScreenPointToRay(touch.position);
		var hit : RaycastHit;
		if (Physics.Raycast (ray, hit, 100)) {
			if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
				var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
				object.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, cameraTransform.z - 0.5));
			}
		}
	}
}

And here’s a Unity Package:
http://dl.dropbox.com/u/9597058/TouchMove.zip

You need to attach a game object into the slot in the inspector (“object”) and the script TouchMove.js will attach the GameObject called “object” to the touch position. TouchMove.js is attached to the main camera. Now, this script isn’t looking at any particular “slot” in the Input.touches list. You will get funny behaviour if you use multiple touches or change touches. For final code, you might want to look only at touch[0] or some such thing, but this is a place to get started with.

Let me know if this works on your Android phone before the scripting becomes more complicated.

The gist of what seems to be going on in that other thread (with Andee’s comments) is that it seems to be doing a raycast down into the game world and seeing if the touch position is over an object, and then setting THAT object - if there is one - to the one you need to move, where as this code just moves the object the coder has set in the inspector.

hey,
It seems to work, atleast the cube is under my finger and not in an arbitrary place :slight_smile:
Basically I wish to just move the cube around on a plane (x,y). In my coming hours then add several objects, which I can move around… The analogy is like a chess game, where I can move objects around on a board.
Than you for your help!
I will try to dissect your code into the stuff explained above .