Roll A Ball 案例学习

Roll A Ball 简单案例记录。以后还有其他不同类型、难易程度不同游戏案例技术点文章也将记录在《Unity游戏案例学习》博文专栏下。

一、主要脚本

1.小球控制脚本(移动及拾取物体得分检测)
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 小球(主角)控制脚本
/// </summary>
public class PlayerControlller : MonoBehaviour
{
    private Rigidbody rb;
    public float playerSpeed = 5f;

    int score = 0;
    public  Text text;
    public GameObject winText;
    void Start()
    {
     
        rb = GetComponent<Rigidbody>();
    }
    //更新事件,Update(),FixUpdate
    void Update()
    {
        //使用系统预设的w,a,s,d 控制Cube移动
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        //  PlayerMovePosition(h,v);
        PlayerMoveAddForce(h, v);
    }
    //方法

    private void PlayerMovePosition(float h,float v)
    {
      
        Vector3 dir = new Vector3(h, 0, v);
        dir = transform.position + dir.normalized *playerSpeed* Time.deltaTime;
        //刚体移动的特点:物体的位置+方向,太快就方向*一个小数,使之慢一点
        rb.MovePosition(dir);
    }

    private void PlayerMoveAddForce(float h, float v)
    {

        Vector3 dir = new Vector3(h, 0, v);
        rb.AddForce(dir * playerSpeed);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "PickUp")
        {
            score++;
            text.text = score.ToString();
            if (score == 10)
            {
                winText.SetActive(true);
            }
            Destroy(other.gameObject);
        }
    }
}
2.摄像机跟随主角移动脚本
using UnityEngine;
/// <summary>
/// 摄像机跟随主角移动脚本
/// </summary>
public class FollowTarget : MonoBehaviour
{
    public Transform playerTranform;
    Vector3 offset;
    void Start()
    {
       offset= transform.position - playerTranform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = playerTranform.position + offset;
    }
}
3.拾取物自身旋转脚本
using UnityEngine;

public class PickUp : MonoBehaviour
{
    void Update()
    {
        transform.Rotate(new Vector3(0, 1, 0) * Time.deltaTime * 60);
    }
}

二、工程层级

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值