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
0
Question by rick-grendel · Aug 17, 2014 at 08:43 AM · physicsfootball

kick a ball

Hello I am making a soccer game I want that the player can shoot the ball by using the left mouse button the problem is i have no script and I ask the community for help not for the whole script but for hints (the whole script is good to) I have explain what i want 1. I want how longer you hold the mouse button pushed how harder you shoot(sorry for the bad sentence) 2. i want a shoot angle between 0 and 20 degrees random

sorry that i have no script

and tank you so much for helping me

Comment
Add comment · Show 3
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 rick-grendel · Aug 17, 2014 at 09:08 AM 0
Share

@JustFun 3D

avatar image Huacanacha · Aug 17, 2014 at 09:49 AM 0
Share

Just track the time the button is depressed then apply force to the ball based on a scaling between $$anonymous$$ and max values.

For the random lift angle: "Random.Range(0,20)". You still need to turn this into a direction vector to use with AddForce.

avatar image rick-grendel · Aug 17, 2014 at 10:47 AM 0
Share

@Huacanacha But I dont know how to do that

2 Replies

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

Answer by JustFun · Aug 17, 2014 at 11:07 AM

This script makes the ball move forward (along z-axis) and bounce after landing. It limits force, applied to ball by tMax. Force is applied only if mouse cursor points the ball.

Attach RigidBody component to the ball, Use Gravity must be checked, adjust Drag value.

 using UnityEngine;
 using System.Collections;
 
 public class KickScript : MonoBehaviour {
 
     public float bounceFactor = 0.9f; // Determines how the ball will be bouncing after landing. The value is [0..1]
     public float forceFactor = 10f;
     public float tMax = 5f; // Pressing time upper limit
 
     private float kickStart; // Keeps time, when you press button
     private float kickForce; // Keeps time interval between button press and release 
     private Vector3 prevVelocity; // Keeps rigidbody velocity, calculated in FixedUpdate()
 
     void Update()
     {
         if(Input.GetMouseButtonDown(0))
         {
             kickStart = Time.time;
         }
         
         if(Input.GetMouseButtonUp(0))
         {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
             if (Physics.Raycast(ray, out hit))
             {
                 if(hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
                     kickForce = Time.time - kickStart;
             }
         }
     }
     
     void FixedUpdate () {
             
         if(kickForce != 0)
         {
             float angle = Random.Range(0,20) * Mathf.Deg2Rad;
             rigidbody.AddForce(new Vector3(0.0f, 
                                            forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Sin(angle),
                                            forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Cos(angle)), 
                                ForceMode.VelocityChange); 
             kickForce = 0;
         }
         prevVelocity = rigidbody.velocity;
             
     }
 
     void OnCollisionEnter(Collision col)
     {
         if(col.gameObject.tag == "Ground") // Do not forget assign tag to the field
         {
             rigidbody.velocity = new Vector3(prevVelocity.x, 
                                              -prevVelocity.y * Mathf.Clamp01(bounceFactor), 
                                              prevVelocity.z);
         }
     }
 
 }

Comment
Add comment · Show 6 · 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 rick-grendel · Aug 17, 2014 at 11:59 AM 0
Share

thank you so much

avatar image DraxxS · Oct 06, 2015 at 08:50 PM 0
Share

Does this script go on the first person controller or the ball itself?

avatar image aycayder · May 06, 2018 at 12:01 AM 0
Share

How can I use these codes for a 2D game? I made some changes on the code. However, I got these errors:

 Assets/Scripts/$$anonymous$$ickTheBall.cs(19,16): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody2D.AddForce(UnityEngine.Vector2, UnityEngine.Force$$anonymous$$ode2D)'
 
 Assets/Scripts/$$anonymous$$ickTheBall.cs(24,30): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody2D.velocity'
 
 Assets/Scripts/$$anonymous$$ickTheBall.cs(53,16): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody2D.velocity'

Here are my codes:

 using UnityEngine;
 using System.Collections;
 
 public class $$anonymous$$ickTheBall : $$anonymous$$onoBehaviour {
     public float bounceFactor = 0.9f; // Deter$$anonymous$$es how the ball will be bouncing after landing. The value is [0..1]
     public float forceFactor = 10f;
     public float t$$anonymous$$ax = 5f; // Pressing time upper limit
 
     private float kickStart; // $$anonymous$$eeps time, when you press button
     private float kickForce; // $$anonymous$$eeps time interval between button press and release 
     private Vector2 prevVelocity; // $$anonymous$$eeps rigidbody velocity, calculated in FixedUpdate()
     [SerializeField]
     private EdgeCollider2D BatCollider;
 
     void FixedUpdate () {
         if(kickForce != 0)
         {
             float angle = Random.Range(0,20) * $$anonymous$$athf.Deg2Rad;
             Rigidbody2D.AddForce(new Vector2(0.0f, 
                 forceFactor * $$anonymous$$athf.Clamp(kickForce, 0.0f, t$$anonymous$$ax) * $$anonymous$$athf.Sin(angle)), 
                 Force$$anonymous$$ode2D.Impulse); 
             kickForce = 0;
         }
         prevVelocity = Rigidbody2D.velocity;
     }
 
     void Update(){
         if(Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space))
         {
             kickStart = Time.time;
         }
 
         if(Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space))
         {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
             if (Physics.Raycast(ray, out hit))
             {
                 if(hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
                     kickForce = Time.time - kickStart;
             }
         }
     }
         
     public void $$anonymous$$ickBall(){
         BatCollider.enabled = true;
     }
 
     void OnCollisionEnter(Collision col)
     {
         if(col.gameObject.tag == "Ground") // Do not forget assign tag to the field
         {
             Rigidbody2D.velocity = new Vector2(prevVelocity.x, 
                 -prevVelocity.y * $$anonymous$$athf.Clamp01(bounceFactor));
         }
     }
 
 }
 
 
 

Your help will be very appreciated. Thank you!

avatar image Eno-Khaon aycayder · May 06, 2018 at 01:13 AM 1
Share

As this is an old question, it's using some depracated functionality. You'll want to make a variable for the Rigidbody2D. For example:

 private Rigidbody2D rb;
 
 void Start()
 {
     rb = GetComponent<Rigidbody2D>();
 }


Then, replace all your current usage of Rigidbody2D (a base class, where you're currently attempting to call functions as if they were static), with rb. This includes, for example:

 rb.velocity = new Vector2(prevVelocity.x, -prevVelocity.y * $$anonymous$$athf.Clamp01(bounceFactor));
avatar image aycayder Eno-Khaon · May 06, 2018 at 02:07 PM 0
Share

Thank you so much! You are wonderful! The script now works properly.

However, I am still unable to kick the ball. I would like the user to be able to kick the ball when he presses on the "space" button. Could the problem be in the following code?

 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;

Here are my all Update function codes:

     void Update(){
         if(Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space))
         {
             kickStart = Time.time;
         }
 
         if(Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space))
         {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
             if (Physics.Raycast(ray, out hit))
             {
                 if(hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
                     kickForce = Time.time - kickStart;
             }
         }
     }
avatar image nebuchednezar · Nov 22, 2021 at 04:49 PM 0
Share

What should i change in this script to kick the ball in the x axis instead of the y axis?

avatar image
0

Answer by ReubenXXX · Jul 24, 2017 at 12:59 AM

basically you are going to only ever have 1 ball in the soccer game so make a variable. this script goes on to the player.

 //drag the ball onto the spot create by this line
 public Gameobject ball; 
 public float power = 0;

 //if mouse button is down
 if(Input.GetMouseButtonDown(0))
 {
        power =+ Time.Deltatime
 {

 //if mouse is not down
 if(!Input.GetMouseButtonDown(0))
 {
      if(power > 0)
      {
          kickball();
      {
   power = 0;
  {

  //when the player is in range to shoot ball
  void Kickball()
  {
      var Vector3 angleX = this.trasform.forward;
      ball.getcomponent<rigidbody>().velocity = new Vector3(angleX.x * power,angleX.y* power + Random.Range(0,20),angleX.z* power);
  }






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

31 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How to face Hovercraft physics 4 Answers

Side scroller, Scripting Bike Controls using hinge joints 0 Answers

FIshing Pole 0 Answers

How can I play audio while a non player controlled object is moving and stops playing when object stands still? 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