简体   繁体   English

在碰撞 Unity2D 时将方向更改为随机方向

[英]change direction into random direction on collision Unity2D

I'm new to unity and I'm trying to create a game where there's a ball that can move in the direction by dragging and releasing on the screen and that change direction randomly when hitting a prefab, I already created that kind of movement but couldn't figure out how to make the ball change direction randomly when hitting the prefab.我是 Unity 的新手,我正在尝试创建一个游戏,其中有一个球可以通过在屏幕上拖动和释放来朝某个方向移动,并且在击中预制件时会随机改变方向,我已经创建了这种运动,但是无法弄清楚如何在击中预制件时使球随机改变方向。 Sorry if this isn't the right place to ask.对不起,如果这不是问的正确地方。

Here's my script这是我的脚本

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

You can get a random angle in radians using Random.Range(0f, 2f * Mathf.PI) and then pass it to Mathf.Cos and Mathf.Sin functions to get a direction with that angle:您可以使用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 ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM