Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by karma0413 · Feb 18 at 04:22 PM · physicsmathballgeometry

How do I calculate the arc of a throw, given two positions and an angle of attack?

I want to save you many hours of research and hours going through physics calculations

PROBLEM:
I have a player on the screen and he moves around a cross-hair target across the ground to the location where he wants to attack another object/player. All I want to tell the ball is where the destination is and what the degree-angle into the air I want to throw the ball and I want the ball do to the rest of the calculations.

SETUP:
Create a script called "ThrowArcBehavior", then create a sphere and apply this script to that sphere..... That's it!!!

You could of course, adjust the gravity, the angle, or anything else, but this should help to get you started!

SPECIAL THANKS TO:
ShervinM, who helped to provide the basis for this code in 3d geometry. Original 2d code and the conversation can be found here: Link To Webpage

CODE:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ThrowArcBehavior : MonoBehaviour
 {
     //Gravity of the simulation
     public float gravity = 9.8f;
     // save CPU resources by only running the code when InFlight=true
     public bool inFlight;
     // the angle thrown into the air
     public float targetInclination;    
     // the destination of our target
     public Vector3 targetDestination;
     
     // IF RUNNING COLLISSIONS ie: if you want to trigger something like "send a message to the player if the ball or rock hits him"
     // the radius to send the collission message
     public float radiusToTrigger;
     // the layerMask to check for collissions.
     private LayerMask layerToCheck;
 
     private Vector3 startPosition;
     private float xVelocity;
     private float yVelocity;
     private float flightDuration;
     private float elapsedTime;
 
     
     // Start is called before the first frame update
     void Start()
     {
         // IF THIS is a Stand-Alone test then run this code below....
         // Vector3 testDestination = new Vector3 (5f,1f,5f);
         // Initialize (45f, testDestination, 5f, LayerMask.GetMask("default"));
         inFlight = true;
         startPosition = transform.position;
         elapsedTime = 0f;
         CalculateVariables();
     }
 
     // Update is called once per frame
     void Update()
     {
         if (inFlight) 
         {
             UpdateProjectilePosition();
         }
         
     }
 
     public void Initialize(float inclination, Vector3 destination, float radiusOfTrigger, LayerMask layerToCheckAgainst) 
     {
         targetInclination = inclination;
         targetDestination = destination;
         radiusToTrigger = radiusOfTrigger;
         layerToCheck = layerToCheckAgainst;
         inFlight = true;
     }
 
     public void CalculateVariables() 
     {
 
         // CALCULATIONS if there are DIFFERENT START and END HEIGHTS
 
         // Calculate the range from the projectile to the target by zero-ing each out in their y-axis
         Vector3 zeroedOrigin = new Vector3(startPosition.x, 0, startPosition.z);
         Vector3 zeroedTarget = new Vector3(targetDestination.x, 0, targetDestination.z);
         Vector3 zeroedDirection = (zeroedTarget - zeroedOrigin).normalized;
 
         float angleRad = targetInclination * Mathf.Deg2Rad;
         float heightDifference = startPosition.y - targetDestination.y;
         float targetDistance = Vector3.Distance(transform.position, targetDestination);
         float targetRange = Vector3.Distance(zeroedOrigin, zeroedTarget);
 
         // Calculate the velocity needed to throw the object to the target at specified angle.
         // Velocity can be solved by re-arranging the general equation for parabolic range:
         // https://en.wikipedia.org/wiki/Range_of_a_projectile
         float projectile_Velocity
             = (Mathf.Sqrt(2) * targetRange * Mathf.Sqrt(gravity) * Mathf.Sqrt(1 / (Mathf.Sin(2 * angleRad)))) /
               (Mathf.Sqrt((2 * targetRange) + (heightDifference * Mathf.Sin(2 * angleRad) * (1 / Mathf.Sin(angleRad)) * (1 / Mathf.Sin(angleRad)))));
 
         // Extract the X  Y componenent of the velocity
         xVelocity = projectile_Velocity * Mathf.Cos(angleRad);
         yVelocity = projectile_Velocity * Mathf.Sin(angleRad);
 
         // Calculate flight time.
         flightDuration = targetRange / xVelocity;
 
         // Rotate projectile to face the target.
         transform.rotation = Quaternion.LookRotation(zeroedDirection);
     }
 
 
     public void UpdateProjectilePosition() 
     {
         if (elapsedTime >= flightDuration) 
         {
             // if we finished our our flight/trajectory of the item thrown, then lets end it
             ProjectileLanded();
             return;
         }
         // However if NOT enough time has elapsed to complete the arc throw....
         
         float x = 0f;
         float y = (yVelocity - (gravity * elapsedTime)) * Time.deltaTime;
         float z = xVelocity * Time.deltaTime;
         // May need to switch around Z and X axis depending on the "forward-direction" of the object
         this.transform.Translate(x, y, z);
         elapsedTime += Time.deltaTime;
     }
 
     public void ProjectileLanded() 
     {
         Debug.Log("This Projectile Landed");
         inFlight = false;
         //Physics.OverlapSphere ()
     }
 }
 


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

219 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Need help with the physics and angles of gerbils in a plastic ball.. 2 Answers

plotting a line which shows a spaceships course 0 Answers

How to find the center of mass from capsulecast 0 Answers

Get a free moving ball. 1 Answer

Calculating surface area of a plane covered by cameras' frustums 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges