Unity3D如何使⽤脚本实现跳跃的效果这⾥介绍的是如何使⽤脚本最简单的模拟出跳跃的效果。
脚本源码如下:
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);
if(Input.GetButtonDown("Jump"))
{
Jump ();
}
}
function Jump ()
unity3d animation{
if(grounded == true)
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
grounded = false;
}
}
function OnCollisionEnter(hit : Collision)
{
grounded = true;
Debug.Log("I'm colliding with something!");
}
其中,这⾏代码尤为重要:
1
如果注释掉这⾏代码,物体在跳跃的时候会出现空中翻转的现象,添加后物体不会出现除了z轴之外的其他旋转。
⼀个完善的⾓⾊移动的脚本源码如下:
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
private var moveDirection : Vector3 = ;
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);
}
如果想添加动画的话,使⽤如下代码即可:
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");
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。