- Home /
How to move a cube to another cube
How to move a cube to another cube when I click the cube.
When I click cube1 I need cube1 to find the position of cube2
Then I need cube1 to go to cube2.
I looked for answers on this but none were easy for me to understand sorry.
Answer by robertbu · Jan 16, 2013 at 05:50 AM
Here is a script that does not involve Raycasts. It moves the object immediately (not over time). If both objects are the same size and shape, then the moved object will seem to disappear (since they are at the same position).
using UnityEngine;
using System.Collections;
public class MoveObjectTo : MonoBehaviour {
public Transform transDest; // Destination
void OnMouseDown() {
transform.position = transDest.position;
}
}
Answer by Sooper1337 · Jan 16, 2013 at 04:02 AM
You can set up a Raycast to detect when the mouse clicks on the cube, then set the transform.position of cube 1 to cube 2.
public Transform cube1;
public Transform cube2;
void Update () {
RaycastHit hit;
if(Input.GetMouseButtonDown(0)){
Ray _Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(_Ray, out hit, 100f)){
GameObject hitObj = hit.collider.gameObject;
if(hitObj.tag == "cube 1"){
cube1.transform.position = cube2.transform.position;
}
}
}
}
Im not asking what to do.. I am asking how to do it.. that is like saying I can do it.. I need an example or a specific reference link.. thanks though
Havnt Had A Chance to test that but it should work. also you will need to set the tags for the cube in order for it to work.
Updated Code works just set each cube to the appropriate transform in the inspector, and set the tag for cube 1 as "cube 1", and it should work when you click cube 1.
wow to move a cube to a cube you need a paragraph of code.. man I thought this engine was easy.. It can not be easy if it relies this much on code. So I guess the engine could have asked me what I wanted to do with the cube when I created it and then gave me more questions to narrow down the tutorials I could then pick from. Hmmm now that would be easier right?
How can I do this without ray stuff? Is it possible to do this in a different way?
Thanks very much for your effort and quick response. I wish for all of us that it was easier and I am sure in time we will get there. Lastly, I have picked this engine for a reason and eventually they will give me more and more reasons to stay with it.
As for my knowledge to actually have it where you click on the cube itself and have some interaction you have to have a ray-cast so unity knows that you are clicking it. if you just want to move the cube when you press $$anonymous$$ouse 1 then you do not have to have ray-casting, although that wasn't what you asked for. If you are just starting out don't get discouraged, over time you will learn it and it will be a lot easier.