Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
1
Question by ramonfr · Dec 12, 2011 at 12:46 AM · rigidbodyaddforcemouseposition

How to apply force to mouse position?

I'm building a soccer game. Once the player has the ball, he is able to kick it to the mouse coordinates.

The problem is:

1 - Once the player has the ball ( "carrying the ball" problem already solved ), when the player clicks on a point of the screen, the ball ( which is a rigidbody ) has to be kicked to this point.

My questions are:

1 - I can't find out how to solve it. Converting 2D coordinates to an 3D space is a mystery to me ( However, I created an sphere which follows the mouse coordinates, so the ball could simply be kicked to the direction of this object in the 3D plane ).

2 - I can't get how to make the rigid.addForce look realistic, like an impulse, how it should be. How can I use the force mode "Impulse"?

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

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by aldonaletto · Dec 12, 2011 at 02:07 AM

Impulse mode adds an instant velocity to the rigidbody in the following proportion: velAdded = force/rigidbody.mass. Physically, it applies instantly the acceleration that the force would produce during one second. It's the best solution in your case, because it will reproduce physically a kick effect even if the ball has an initial velocity in any direction.
You can convert mouse coordinates to world point using Input.mousePosition, ScreenPointToRay and Physics.Raycast, then calculate the desired direction and apply the force:

var ball: Transform; // drag the ball here var force: float = 50; // change the force when needed

function Update () { if (Input.GetButtonDown("Fire1")){ // Create a ray from the current mouse coordinates var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit: RaycastHit; // if something tagged "Ground" is hit... if (Physics.Raycast(ray, hit) && hit.transform.tag == "Ground"){ var dir = hit.point - ball.position; // calculated the direction... // and kick! ball.rigidbody.AddForce(dir.normalized * kickForce, ForceMode.Impulse); } } } IMPROVED VERSION: The script above kicks the ball in the clicked point direction, but the force must be controlled somehow by the player to make the ball reach the desired point, and you have no control over the elevation angle. If you want the ball to fall precisely in the clicked point, you can use the version below, where the function KickForce calculates the desired force and direction:

var ball: Transform; // drag the ball here

function KickForce(dest: Vector3, angle: float): Vector3 { var dir = dest - ball.position; // get target direction var h = dir.y; // get height difference dir.y = 0; // retain only the horizontal direction var dist = dir.magnitude ; // get horizontal distance var a = angle Mathf.Deg2Rad; // convert angle to radians dir.y = dist Mathf.Tan(a); // set dir to the elevation angle dist += h / Mathf.Tan(a); // correct for small height differences // calculate the velocity magnitude var vel = Mathf.Sqrt(dist Physics.gravity.magnitude / Mathf.Sin(2 a)); return vel dir.normalized ball.rigidbody.mass; }

// control the kick angle when needed: the greater the angle, the slower the kick var kickAngle: float = 15;

function Update(){ if (Input.GetButtonDown("Fire1")){ // Create a ray from the current mouse coordinates var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit: RaycastHit; // if something tagged "Ground" is hit... if (Physics.Raycast(ray, hit) && hit.transform.tag == "Ground"){ var kForce = KickForce(hit.point, kickAngle); // calculate the force and kick! ball.rigidbody.AddForce(kForce, ForceMode.Impulse); } } } NOTE: The current ball velocity will be added to the kick velocity, thus the destination point may not be reached; if this is the case, replace the last Update() line with ball.rigidbody.velocity = kForce; and remove the ball.rigidbody.mass from the last KickForce() line.

Comment
Add comment · Show 2 · Share
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
avatar image rnodal · Jan 09, 2012 at 04:10 AM 0
Share

Thank you for this answer.

avatar image timzydee · Mar 28, 2013 at 08:19 PM 0
Share

Thanks for this simple little script. I've been looking for this exact thing for days. All I found was one that moved the ball to the click point then it stopped. This is what I needed, where the ball keeps moving.

avatar image
0

Answer by alok-kr-029 · Jan 18, 2014 at 04:09 AM

pragma strict

ar ball: Transform; // drag the ball here var play : boolean =false;

function KickForce(dest: Vector3, angle: float): Vector3 { var dir = dest - ball.position; // get target direction var h = dir.y; // get height difference dir.y = 0; // retain only the horizontal direction var dist = dir.magnitude ; // get horizontal distance var a = angle Mathf.Deg2Rad; // convert angle to radians dir.y = dist Mathf.Tan(a); // set dir to the elevation angle dist += h / Mathf.Tan(a); // correct for small height differences // calculate the velocity magnitude var vel = Mathf.Sqrt(dist Physics.gravity.magnitude / Mathf.Sin(2 a)); return vel dir.normalized ball.rigidbody.mass; }

// control the kick angle when needed: the greater the angle, the slower the kick var kickAngle: float = 15;

function Update() { if (Input.touchCount > 0) { for ( var touch : Touch in Input.touches) { switch (touch.phase) { case TouchPhase.Began : var ray1: Ray = Camera.main.ScreenPointToRay(touch.position); var hit: RaycastHit; // if something tagged "Ground" is hit... if (Physics.Raycast(ray1, hit) ) { if(hit.transform.name=="ball") play=true; } break; case TouchPhase.Ended : if(play== true) {
var ray: Ray = Camera.main.ScreenPointToRay(touch.position); var hit1: RaycastHit; // if something tagged "Ground" is hit... if (Physics.Raycast(ray, hit1) ) { print(hit1.transform.name); var kForce = KickForce(hit1.point, kickAngle); // calculate the force and kick! ball.rigidbody.AddForce(kForce, ForceMode.Impulse); } play= false; } break; } } }

 if(Input.GetMouseButtonDown(0)){
   

} }

Comment
Add comment · Share
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

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

7 People are following this question.

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

Related Questions

3D mouse position 0 Answers

Little Question regarding rigidbody gravity and addforce. 2 Answers

AddForce vs MovePosition Rigidbody. 2 Answers

Character Jumping 2 Answers

Addforce to RigidBody problem 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