unity3D--跑酷小游戏(一)

导入资料和模型

选择自己喜欢的人物,对人物添加刚体和碰撞体;刚体(为了人物可以弹跳);碰撞体(与障碍物和地面碰撞)

为人物添加跳的动作,按下空格键,人物跳起

public class playerController : MonoBehaviour
{
    private Rigidbody rb;
    public  float jumpForce;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
       
    }
}

人物起跳会发现可以在空中按下空格键连续跳和回落很慢的问题,解决方案:判断如果人物在地面上才可以实现按下空格键人物起跳和加大重力;

public class playerController : MonoBehaviour
{
    private Rigidbody rb;
    public  float jumpForce;
    public float gravityModifier;
    public bool isGround;//默认是false;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        //增加物体本身的重力,加快回落的速度
        Physics.gravity *= gravityModifier;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)&&isGround) {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGround = false;

        }
       
    }
    //刚刚触碰物体时
    private void OnCollisionEnter(Collision collision)//除本身之外碰撞的物体
    {
        isGround = true;
    }
}

添加障碍物,对障碍物添加碰撞体组件,并且使障碍物向左移动

 1 public class moveLeft : MonoBehaviour
 2 {
 3     public float speed = 30;
 4     // Start is called before the first frame update
 5     void Start()
 6     {
 7         
 8     }
 9 
10     // Update is called once per frame
11     void Update()
12     {
13         // Time.deltaTime 时间的修订,在不同的设备上,保持一致
14         //Vector3.left*speed 以一个速度向左移动
15         transform.Translate(Vector3.left*speed*Time.deltaTime);
16     }
17 }

上述代码中,出现了障碍物穿过人物,但没有被撞飞????有人说,是因为速度太大的原因,小伙伴可以解决一下这个问题,我调小了速度,但还是穿过去了;

添加障碍物的预制件

循环产生障碍物:首先创建一个空物体,位置reset一下,命名为Spawn Manager,在创建对应的脚本

public class spawnManager : MonoBehaviour
{
    public GameObject obstaclePrefab;//循环产生障碍物的预制体
    public Vector3 spawnPos = new Vector3(20, 0, 0);
    public float starDelay, repeatRate;
    // Start is called before the first frame update
    void Start()
    {
        //复制产生(函数:产生复制的障碍物,开始延迟时间,重复率)
        InvokeRepeating("SpawnObstacle",starDelay,repeatRate);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //生成多个障碍物
    public void SpawnObstacle()
    {
        //生成函数(生成的物体,生成的坐标,以怎样的方向生成);
        Instantiate(obstaclePrefab,spawnPos,Quaternion.identity);
    }
}

将Hierarchy中的Obstacle删掉就可以了;在inspector中,spawnManager脚本下的Obstacle Prefab中,关联障碍物的预制体

出现的问题:人物跳不动,跳的很矮,也撞不飞。

posted @ 2021-10-10 22:20  无敌小金刚  阅读(393)  评论(0)    收藏  举报