- Home /
Controlling two object with one Javascript
I want to control my two object with one script (different key). I thought, I should define one control setting to one of my object and another controller setting for another object.
(w,a,s,d) for one object (up,down,left,right) for another object.
How can i do it?
Answer by OrbitSoft · Dec 07, 2013 at 08:15 PM
It's pretty easy using Input.GetKey and KeyCode(which contains values for letters, arrows etc.)
var Object1 : Transform;
var Object2 : Transform;
function Update()
{
// WASD
if (Input.GetKey(KeyCode.W))
{
Object1.transform.position.Translate(x,y,z);
}
if (Input.GetKey(KeyCode.A))
{
Object1.transform.position.Translate(x,y,z);
}
if (Input.GetKey(KeyCode.S))
{
Object1.transform.position.Translate(x,y,z);
}
if (Input.GetKey(KeyCode.D))
{
Object1.transform.position.Translate(x,y,z);
// substitute all the x,y,z with wanted values (try 0.05)
}
// Arrows
if (Input.GetKey(KeyCode.UpArrow))
{
Object2.transform.position.Translate(x,y,z);
}
// And so on.. Just substitute UpArrow with DownArrow, Left Arrow and Right Arrow
}
Thats a lot of code dublication. What if you have 4 players? ) Use variables ins$$anonymous$$d of $$anonymous$$eyCode and you can use same script for different objects
Answer by FPSworrior · Dec 07, 2013 at 08:30 PM
All you have to do is change the axis. Make it where you vertical and horizontal axis only work with w,a,s,d and then you make two more axis called horizontal 2, and vertical 2. Make those only work with up arrow, down arrow, left arrow, right arrow. You write the code like this.
if(Input.GetAxis("Horizontal"))
{
//Move left and right
}
if(Input.GetAxis("vertical"))
{
//Move forward and back
}
If you would like I can provide more sample code for you, and show you how to change the axis.
Your answer
Follow this Question
Related Questions
Setting a variable to an instantiated object. 1 Answer
Drawing a 3D object javascipt 0 Answers
Disable GameObject Only Father Not Children 2 Answers
Making a rigidbody cube snap 90 deg at a time 1 Answer
Setting Scroll View Width GUILayout 1 Answer