- Home /
How do you move a cube with javascript
Hi guys, I am new to Unity and I wanted to ask how do I translate the position of a cube that I made with script. I am just testing out small little scripts to see how things work. Here is my code:
var myCube: GameObject;
var charCube: GameObject;
var x = 0;
var y = 1;
var z = 0;
function Start () {
var aPositions : Array = [new Vector3(0,0,0),
new Vector3(0,0,1),
new Vector3(0,0,2),
new Vector3(0,0,3),
new Vector3(0,0,4),
new Vector3(1,0,1),
new Vector3(1,0,2),
new Vector3(1,0,3),
new Vector3(1,0,4)];
var rot : Quaternion = Quaternion.identity;
for(var i=0; i<aPositions.length; i++)
{
Instantiate(myCube, aPositions[i], rot);
}
Instantiate(charCube, new Vector3(x,y,z), rot);
}
function Update () {
if (Input.GetButtonDown("Vertical"))
//I want the charCube to move forward if I pressed 'w'.
}
I tried a lot of things and I am sure that it is not too difficult. But I just can't wrap my finger around it. Any help would be appreciated. Thanks guys!
Answer by Peterw301 · Nov 14, 2012 at 08:05 PM
function Update() {
// Move the object forward along its z axis 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);
// Move the object upward in world space 1 unit/second.
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
look at http://docs.unity3d.com/Documentation/ScriptReference/Transform.Translate.html for more :)
I actually tried that. Well, I guess I should be clearer. So each myCube is like a tile. So if I wanted charCube to move from tile to tile ins$$anonymous$$d of move forward an indefinite amount, how should I go about it without using Lerp. As of now, charCube is Vector3(x, y, z) where x = 0, y=1, z=0 and I would like each time I press W, x+=1.
Answer by Screenhog · Nov 14, 2012 at 08:05 PM
If it's just a case of moving it, you'll want Transform.Translate.
However, if you want it to detect collisions on the way, then that probably won't work for you, and you'll need to do some kind of physics-based solution, like Rigidbody.AddForce.
Your answer
![](https://koobas.hobune.stream/wayback/20220613083848im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make a Cube with a texture in a JavaScript? 0 Answers
Up and Down Cubes Shaking Issue. 0 Answers
Start Animation in code is not working 1 Answer
Making cube a child of an object. 1 Answer
Detect face of cube clicked 4 Answers