2d角色跳跃 unity3d

2017-02-13 14:30:00 weixin_33767813 阅读数 735
using UnityEngine;
using System.Collections;

public class HeroColtrol : MonoBehaviour
{
    private Rigidbody2D HeroRd;
    public float MoveSpeed;
    public float JumpHeight;
    void Awake()
    {
        HeroRd = transform.GetComponent<Rigidbody2D>();
    }


    void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        if (!h.Equals(0))
        {
            HeroRd.velocity = new Vector2(h * MoveSpeed, HeroRd.velocity.y);
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (HeroRd.velocity.y.Equals(0))
                HeroRd.velocity = new Vector2(HeroRd.velocity.x, JumpHeight);
        }

    }

}

img_b31e84f622515094669153d0387f082d.png
图片.png
2014-10-21 23:38:28 book_longssl 阅读数 23358


这里介绍的是如何使用脚本最简单的模拟出跳跃的效果。

脚本源码如下:

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


2020-03-18 22:46:15 pointeryang 阅读数 240

大家好,很高兴和大家分享我们的Unity游戏开发经验, 这是我们的系列视频的第三期视频, 在这期视频中,我们将在Unity中使用C#脚本来实现角色的跳跃,包括跳跃代码的改进,让角色跳跃更加真实,同时也为后面的游戏开发做准备。 不管您是否有Unity的使用和开发经验, 都希望这段视频对您有帮助。

Unity2D游戏开发基础(三)控制角色——跳跃

2020-02-06 11:57:23 weixin_42189888 阅读数 858

参考:https://www.bilibili.com/video/av82865782?t=818

直接贴代码

playerController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour
{
    public Rigidbody2D rb;
    public Collider2D coll;
    public Animator anim;
    public float jumpforce ,speed;

    public Transform groundCheck;
    public LayerMask ground;//碰撞体过滤 

    public bool isGround, isJump;

    bool jumpPressed;
    int jumpCount;
    
    
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<Collider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump") && jumpCount > 0)
        {
            jumpPressed = true;
        }
        
    }

    //每秒固定执行的操作,与设备无关
    private void FixedUpdate()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);//判断是否在地面
        GroundMovement();
        SwitchAnim();
        Jump();
    }

    //根据输入控制水平方向的移动和以及方向变化
    void GroundMovement()
    {
        float horizontalMove = Input.GetAxisRaw("Horizontal");//只有0 -1 1 三个数字
        rb.velocity = new Vector2(horizontalMove * speed, rb.velocity.y);

        if (horizontalMove != 0)
        {
            transform.localScale = new Vector3(horizontalMove, 1, 1);//控制翻转
        }
       
    }

    void Jump()
    {
        
        if (isGround)
        {
            jumpCount = 2;//在地面的时候就恢复可跳跃次数
            isJump = false;
        }

        if(jumpPressed && isGround)
        {
            isJump = true;
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            jumpCount--;
            jumpPressed = false;//每0.02秒检测按键是否松开
            
        }

        else if (jumpPressed && jumpCount > 0 && !isGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            jumpCount--;
            jumpPressed = false;
            
        }

    }

    //控制动画转移
    void SwitchAnim()
    {
        //判断是否跑
        anim.SetFloat("running", Mathf.Abs(rb.velocity.x));
        //判断下落还是上跳
        anim.SetFloat("jumping", rb.velocity.y);
        //判断是否返回静止状态
        if (isGround)
        {
            anim.SetBool("idle", true);
        }
        else
            anim.SetBool("idle", false);


    }


   
}

在这里插入图片描述

2018-07-27 18:18:52 u013628121 阅读数 3661
using UnityEngine;
using UnityEngine.AI;

public class SpaceJump : MonoBehaviour
{
    public float distance = 5f;
    public float hight = 8f;
    public float useTime = 1.5f;
    public KeyCode JumpKeyCode = KeyCode.Space;
    public bool isJumping = false;//是否在跳跃中
    public bool isContinueJump = true;//是否允许连跳
    public int jumpCountMax = 5;//最高允许连跳几次
    public int currJumpCount = 0;//当前连跳次数
    Vector3 addForce;
    private Rigidbody rigidbody;
    private NavMeshAgent agent;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
        agent = GetComponent<NavMeshAgent>();
    }

    void FixedUpdate()
    {
        if (Input.GetKeyDown(JumpKeyCode)) Jump();
        if (isJumping && rigidbody && rigidbody.velocity.y == 0) JumpOver();// 落地
    }

    /// <summary>
    /// 跳跃结束
    /// </summary>
    public void JumpOver()
    {
        isJumping = false;
        if (rigidbody)
        {
            currJumpCount = 0;
            addForce = Vector3.zero;
            rigidbody.velocity = Vector3.zero;
        }
    }

    void iTweenJump()
    {
        Vector3 p2;//角色落点
        Vector3 p1;//最高点
        Vector3 dir = GetToMouseDir();//方向是跳向鼠标,transform.forward是跳向前方
        p1 = transform.position + dir * (distance / 2) + transform.up * hight;//第二个点:起始位置前方几米处上方几米的坐标.
        p2 = transform.position + dir * distance;
        //找到碰撞器 落脚点
        RaycastHit raycastHit; //碰撞体信息
        if (Physics.Raycast(p2, Vector3.down, out raycastHit, 81f))
        {
            p2 = raycastHit.point;
        }
        Vector3[] paths = new Vector3[3];
        paths[0] = transform.position;
        paths[1] = p1;
        paths[2] = p2;
        iTween.MoveTo(gameObject, iTween.Hash("path", paths, "movetopath", true, "time", useTime, "oncomplete", "JumpOver"));//movetopath=false按点移动,=true按照点构成的曲线路径移动
    }

    /// <summary>
    ///角色坐标 到 鼠标位置的方向
    /// </summary>
    Vector3 GetToMouseDir()
    {
        Vector3 dir = Vector3.forward;
        //从射相机的近裁剪面 开始并穿过 屏幕中鼠标像素坐标 的射线,从摄像机通过一个屏幕点的射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        if (Physics.Raycast(ray, out hit))
        {
            Vector3 hitPos = hit.point;
            Vector3 playerPos = transform.position;
            //向量减法 和y无关,所以同步一下高度
            playerPos.y = hitPos.y;
            //向量减法,得到一个向量,包含方向和距离
            dir = (hitPos - playerPos);
            //归一化 去除距离 ,只要方向,如果不去除距离 ,那么角色闪到鼠标点击的位置
            dir = dir.normalized;
        }
        return dir;
    }

    void RigidbodyJump()
    {
        if (isJumping)
        {
            if (isContinueJump)
            {
                if (currJumpCount >= jumpCountMax)
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }
        currJumpCount += 1;
        //打开刚体移动
        rigidbody.constraints = RigidbodyConstraints.None;
        rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
        //角色当前刚体速度
        float xSpeed = 0;
        float zSpeed = 0;
        if (agent == null || agent.enabled == false)
        {
            xSpeed = rigidbody.velocity.x;
            zSpeed = rigidbody.velocity.z;
        }
        else
        {
            xSpeed = agent.velocity.x;
            zSpeed = agent.velocity.z;
            agent.enabled = false;
        }
        Vector3 add;
        if (xSpeed == 0 && zSpeed == 0)
        {//站立状态:向上眺
            add = transform.up * hight;
            rigidbody.velocity += add;
        }
        else
        {//移动状态:向鼠标方向跳
            Vector3 dir = GetToMouseDir();
            add = dir * distance + transform.up * hight;
            if (addForce == Vector3.zero)
            {//判断是第一次跳跃,就跳固定值高度
                rigidbody.velocity = add;
            }
            else
            {
                rigidbody.velocity += add;
            }
        }
        addForce += add;
        //Debug.LogError("Rigidbody" + GetComponent<Rigidbody>().velocity+"zSpeed:" + zSpeed+ "xSpeed:"+ xSpeed+"dir:" + dir+"add"  + add+"rigidbody.velocity = " +rigidbody.velocity + "force" + addForce);
        rigidbody.AddForce(addForce);
        // 设置 角色状态  动画 等为跳跃
    }

    public void Jump()
    {
        if (rigidbody)
        {
            RigidbodyJump();
        }
        else
        {
            iTweenJump();
        }
        isJumping = true;
    }

}