While I know almost nothing about JavaScript, I have managed to cobble together a code that will move a game object (The player. I use a rigidbody) when a GUI button is pressed.
The purpose of this is to allow me to try and make a simple game that could theoretically be used on a touch screen device by way of a “Virtual D-pad”
While it works thus far – I am unable to get the object to rotate and face the direction that it is moving.
If it is of any benefit – The character moves in the X and Z axis along the ground.
This is code used:
var customButton : GUIStyle;
var person : GameObject;
function OnGUI () {
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if (GUI.RepeatButton(Rect (0,180,Screen.width / 2,60), "", customButton))
{
person.transform.Translate(-0.05,0,0);
}
}
As it stands, I use 4 variants of this code as separate JavaScript objects to control the player (Condensing them into one will be the next stage, but if you think it would be simpler to do now, please do not hesitate to say!)
Any further details and I will happily try to give them.
Thanks
I also apologise that this is similar to many other questions, but I tried to implement the various solutions to no effect.
person.transform.forward is the direction the person is facing. use person.transform.LookAt(some position in the world) to get it to face that way. Do something like person.transform.position += person.transform.forward * Time.deltaTime * speed to move the person in the direction he is facing.
Instead of moving the character in each direction separately, you can turn the character in the direction you want, then move it always forward:
var speed:float = 4;
if (GUI.RepeatButton(Rect (0,180,Screen.width / 2,60), "", customButton))
{
person.transform.forward = -Vector3.right;
person.transform.Translate(0,0,speed*Time.deltaTime);
}
if (GUI.RepeatButton(Rect (...), "", customButton)) // right
{
person.transform.forward = Vector3.right;
person.transform.Translate(0,0,speed*Time.deltaTime);
}
if (GUI.RepeatButton(Rect (...), "", customButton)) // forward
{
person.transform.forward = Vector3.forward;
person.transform.Translate(0,0,speed*Time.deltaTime);
}
if (GUI.RepeatButton(Rect (...), "", customButton)) // back
{
person.transform.forward = -Vector3.forward;
person.transform.Translate(0,0,speed*Time.deltaTime);
}
Using Time.deltaTime you can have a constant velocity, independent of frame rate. You can test other values for speed in the Inspector.
This is not the most efficient code in the world, but match what you already had.