简体   繁体   中英

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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