Unity3D如何使用脚本实现跳跃的效果

欢迎来到unity学习unity培训unity企业培训教育专区,这里有很多U3D资源U3D培训视频U3D教程U3D常见问题U3D项目源码,我们致力于打造业内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);
        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!");
}
其中,这行代码尤为重要:


1
transform.rotation = Quaternion.LookRotation(Vector3.forward, Vector3.up);
如果注释掉这行代码,物体在跳跃的时候会出现空中翻转的现象,添加后物体不会出现除了z轴之外的其他旋转。

一个完善的角色移动的脚本源码如下:

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);        
        
}
如果想添加动画的话,使用如下代码即可:

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");
        }
}


更多精彩请点击 http://www.gopedu.com/
原文地址:https://www.cnblogs.com/Unity3Dqishituan/p/4041879.html