分享一个自己写的适合初学者的类似乒乓球的小游戏

直接上代码通过使用Vector3.Reflect方法实现游戏物体的反射

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

public class Ball : MonoBehaviour
{
    private Vector3 dir = new Vector3(-1,1,0).normalized;
    void Start () {

    }   
    // Update is called once per frame
    void Update ()
    {
        transform.Translate(dir * Time.deltaTime * 2);
    }
    void OnCollisionEnter(Collision other)
    {
        if (other.collider.tag == "UpWall")
        {
            Debug.Log(0);
            dir = Vector3.Reflect(dir, Vector3.up);
        }
        else if (other.collider.tag == "RightWall")
        {
            Debug.Log(0);
            dir = Vector3.Reflect(dir, Vector3.right);
        }
    }
}

使用检测碰撞来触发相关的事件 特别注意的是碰撞器和触发器的区别,这个度娘有总结

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

public class Power : MonoBehaviour {
    Vector3 force =new Vector3 (0.5f,0,0.1f);

    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Gui.star )
        {
            AddForec(force);

        } 
    }

    void AddForec( Vector3 force)
    {
        Rigidbody bulletRig = GetComponent<Rigidbody>();
        bulletRig.AddForce(force * 10, ForceMode.Force );
    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.transform.CompareTag("Player1"))
        {
            Debug.Log(2);
            force = Vector3.Reflect(force , Vector3.right  );

        }
        if (collision.transform.CompareTag("Player2"))
        {
           Gui .player1++;
            Application.LoadLevel(0);
            // force = Vector3.Reflect(force, Vector3.left);
            Destroy(gameObject);
        }
        if (collision.transform.CompareTag("Boll"))
        {
            Gui . player2++;
            Application.LoadLevel(0);
            Destroy(gameObject);
            //force = Vector3.Reflect(force, Vector3.right );

        }
        if (collision.transform.CompareTag("Boll1"))
        {
            Debug.Log(1);
            force = Vector3.Reflect(force, Vector3.forward);

        }
    }
}

刚开始使用CSDN操作不熟悉直接上源码链接:http://pan.baidu.com/s/1jIMiWZk 密码:ktlh

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值