Welcome to Unity Learning, unity training, Unity Enterprise training and education zone, there are many u3d resources, u3d training videos, u3d tutorials, U3d Frequently asked questions, U3d Project source code, we are committed to creating the industry Unity3d training, learning the first brand.
Here is how to use the simplest of scripts to simulate the effect of jumping.
The script source code is as follows:
var speed = 3.0; This data type is a float.
var jumpspeed = 50.0;
var grounded = true;
function Update ()
{
var X:vector3 = Input.getaxis ("horizontal") * transform.right * time.deltatime * speed;
var Z:vector3 = Input.getaxis ("Vertical") * Transform.forward * time.deltatime * speed;
Transform. Translate (Input.getaxis ("horizontal"), 0, Input.getaxis ("Vertical"));
Transform. Translate (x + z);
Transform.rotation = Quaternion.lookrotation (Vector3.forward, vector3.up);
if (Input.getbuttondown ("Jump"))
{
Jump ();
}
}
Function Jump ()
{
if (grounded = = true)
{
Rigidbody. Addforce (Vector3.up * jumpspeed);
Grounded = false;
}
}
function Oncollisionenter (hit:collision)
{
Grounded = true;
Debug.Log ("I ' m colliding with something!");
}
Where this line of code is particularly important:
1
Transform.rotation = Quaternion.lookrotation (Vector3.forward, vector3.up);
If you comment out this line of code, the object will appear in the air when jumping, the object will not appear in addition to the z axis of rotation.
A perfect role to move the script source code is as follows:
var speed:float = 6.0;
var jumpspeed:float = 8.0;
var gravity:float = 20.0;
private var Movedirection:vector3 = Vector3.zero;
function Update ()
{
var Controller:charactercontroller = getcomponent (Charactercontroller);
if (controller.isgrounded)
{
Movedirection = Vector3 (Input.getaxis ("horizontal"), 0, Input.getaxis ("Vertical")); Allows for player input
Movedirection = transform. Transformdirection (movedirection); How to move
Movedirection *= speed; How fast to move
if (Input.getbutton ("Jump"))
{
MOVEDIRECTION.Y = Jumpspeed;
}
}
Apply Gravity
MOVEDIRECTION.Y-= gravity * time.deltatime;
Move the Controller
Controller. Move (movedirection * time.deltatime);
}
If you want to add animations, use the following code:
function Update ()
{
if (Input.getkey ("D") | | Input.getkey ("right"))
{
Animation. Play ("RUNFWD");
}
else if (Input.getkey ("a") | | Input.getkey ("left"))
{
Animation. Play ("RUNBKWD");
}
else if (Input.getkey ("W") | | Input.getkey ("Up"))
{
Animation. Play ("Strafel");
}
else if (Input.getkey ("s") | | Input.getkey ("Down"))
{
Animation. Play ("Strafer");
}
Else
{
Animation. Crossfade ("Idle");
}
}
For more highlights, please click http://www.gopedu.com/
Unity3d How to use a script to achieve a jump effect