I have script for crouching when i press and hold S its crouching when i release the button the player gets in his normal size. Now i want to do the same thing with touch button but i cant figure how to do that, can some1 help?
static var vScale = 1.0;
private var tr: Transform;
private var dist: float; // distance to ground
function Start(){
tr = transform;
var ch:CharacterController = GetComponent(CharacterController);
dist = ch.height/2; // calculate distance to ground
}
function Update()
{
vScale = 1.0;s
if (Input.GetKey("s")){ // press s to crouch
vScale = 0.5;
}
var ultScale = tr.localScale.y; // crouch/stand up smoothly
tr.localScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5*Time.deltaTime);
tr.position.y += dist * (tr.localScale.y-ultScale); // fix vertical position
}
function OnGUI ()
{
}
[3])
Refactor your Update code to call functions `Crouch` and `Stand`. To make sure your script works like before, use [Input.GetKeyDown][4] and Input.[GetKeyUp][5]. (See *[code changes][6]*)
Then add a [Button][7] to your scene. Since my example has Crouch and Stand functions, I add an [EventTrigger][8] to the button and hook up **Pointer Down** and **Pointer Up** events to route to **Crouch** and **Stand**. The setup on the button look like this:
<img src="https://dl.dropboxusercontent.com/u/86837997/answers-images/CrouchEventTrigger.png">
When you touch or press the mouse, the following happens.
**Red arrow:** *EventSystem* send events to button and is intercepted by *EventTrigger*.
**Green dotted line:** *EventTrigger* has references to the *Crouch Example* game object.
*Edit: Ignore the green dotted line to the script. It just means that the script sits on that game object...*
**Blue arrow:** *EventTrigger* routes *Pointer Down* and *Pointer Up* events to *Crouch* and *Stand*.
[1]: https://github.com/devmelon/Answers/tree/8072340d2020f9d98acd2f0e615201c15136905a
[2]: https://github.com/devmelon/Answers/commits/8072340d2020f9d98acd2f0e615201c15136905a
[3]: https://github.com/devmelon/Answers/blob/8072340d2020f9d98acd2f0e615201c15136905a/Assets/Answers/Pejovski/CrouchExample.js
[4]: http://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
[5]: http://docs.unity3d.com/ScriptReference/Input.GetKeyUp.html
[6]: https://github.com/devmelon/Answers/commit/1235f21fc40ae5109cf288a72d5bb8a62e07f3eb?diff=split
[7]: http://docs.unity3d.com/Manual/script-Button.html
[8]: http://docs.unity3d.com/Manual/script-EventTrigger.html