Skip to content
Snippets Groups Projects
TestScript.cs 1.47 KiB
Newer Older
william's avatar
william committed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestScript : MonoBehaviour {

    private Animator stateMachine;

    [SerializeField] private GameObject ball;
    [SerializeField] private GameObject target;
    [SerializeField] private Transform throwPoint;
    [SerializeField] private GameObject player;

    private Animator playerAnimator;

    private void Start()
    {
        playerAnimator = player.GetComponent<Animator>();
    }

    // Update is called once per frame

    public void shoot(float force)
    {
        float xdistance;
        float time = 0.8f + force;
        xdistance = target.transform.position.x - throwPoint.transform.position.x;
        float ydistance;
        ydistance = target.transform.position.y - throwPoint.transform.position.y;

        float throwAngle; 
        throwAngle = Mathf.Atan((ydistance + calculateGravity() * (time * time)) / xdistance);
        float totalVelo = xdistance / (Mathf.Cos(throwAngle) * time);

        float xVelo, yVelo;
        xVelo = totalVelo * Mathf.Cos(throwAngle);
        yVelo = totalVelo * Mathf.Sin(throwAngle);

        GameObject bulletInstance = Instantiate(ball, throwPoint.transform.position, throwPoint.rotation) as GameObject;
        bulletInstance.GetComponent<Rigidbody2D>().velocity = new Vector2(xVelo, yVelo);
        playerAnimator.SetTrigger("DefTurn");
    }

    private float calculateGravity()
    {
        return Physics2D.gravity.y / -2;
    }
}