【问题标题】:change direction into random direction on collision Unity2D在碰撞Unity2D时将方向更改为随机方向
【发布时间】:2021-10-17 05:57:08
【问题描述】:

我是 Unity 的新手,我正在尝试创建一个游戏,其中有一个可以移动的球 通过在屏幕上拖动和释放以及在击中预制件时随机改变方向的方向,我已经创建了这种运动,但无法弄清楚如何让球在击中预制件时随机改变方向。 抱歉,如果这不是问的正确地方。

这是我的脚本

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

public class Player : MonoBehaviour
{
    [SerializeField] private float power = 2;
    [SerializeField] private Vector2 minPow, maxPow;
    public Vector3 force;
    private Vector3 startPoint, endPoint;
    private Rigidbody2D rb;
    private Camera cam;
    private Aim aim;

    void Start()
    {
        cam = Camera.main;
        rb = GetComponent<Rigidbody2D>();
        aim = GetComponent<Aim>();
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            startPoint.z = 15;
        }

        if(Input.GetMouseButton(0))
        {
            Vector3 currentPos = cam.ScreenToWorldPoint(Input.mousePosition);
            startPoint.z = 15;
            aim.RenderLine(startPoint, currentPos);
        }

        if(Input.GetMouseButtonUp(0))
        {
            endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            endPoint.z = 15;

            force = new Vector3(Mathf.Clamp(startPoint.x - endPoint.x, minPow.x, maxPow.x), Mathf.Clamp(startPoint.y - endPoint.y, minPow.y, maxPow.y));
            rb.AddForce(force * power, ForceMode2D.Impulse);
            aim.EndLine();
        }
    }
    public void BoostUp(float pow)
    {
        rb.velocity *= pow;
    }
}



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

public class Boost : MonoBehaviour
{
    [SerializeField] float pow;
    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        {
            Player player = other.GetComponent<Player>();
            if(player != null)
            {
                player.BoostUp(pow);
                Destroy(this.gameObject);
            }
        }
    }
}

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    您可以使用Random.Range(0f, 2f * Mathf.PI) 获得一个以弧度为单位的随机角度,然后将其传递给 Mathf.CosMathf.Sin 函数以获得具有该角度的方向:

    float angle = Random.Range( 0f, 2f * Mathf.PI );
    Vector2 direction = new Vector2( Mathf.Cos( angle ), Mathf.Sin( angle ) );
    

    【讨论】:

      猜你喜欢
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多