Need help on a throw/hit script

Updated on January 5, 2018 in Unity
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on January 4, 2018

Hello 🙂 

I work on a little game for some time now, it is a soccer game. I am a begginer in scripting and here comes my problem :/ I made the environment but I didn’t find any tuto on a script that would hit the ball forward when user press mouse left click on the ball. I past hours and hours on it and nothing works. The only script that I tried and who works a bit is the following : 

 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class HitBall : MonoBehaviour {
 public Rigidbody rb;
 // Update is called once per frame
 void FixedUpdate () {
 if( Input.GetMouseButtonDown(0))
 {
 RaycastHit hit;
 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 
if (Physics.Raycast(ray, out hit))
 {
 BoxCollider bc = hit.collider as BoxCollider;
 if (bc != null)
 {
 rb.AddForce(0, 0, 200);
 }
 }
 }
}
}
 

It works but it doesn’t really do what I want, it simply push the ball when I click left mouse button in a way completly independant of the ball position compared to mine. Indeed the final project I want to realise is approximately like this : https://www.youtube.com/watch?v=9yUOpsKucyI

Can someone please help me by sending me on a appropriate documentation or something about how I can change the script.

Thank you for your help, have a nice day

  • Liked by
Reply
0 on January 5, 2018

First of all, to put physics based things in FixedUpdate is correct, but don’t put a Input related function there. It could happen that the player pressed at a frame where the script is not checking if the player has pressed. So use Update instead.

Second, if you want that the ball flies in the direction where you look at, you have to change your rb.AddForce to the following:

rb.AddForce(Camera.main.transform.forward);
//or
rb.AddForce(ray.direction);

 

  • Liked by
Reply
Cancel
0 on January 5, 2018

Thank you for your reply. Actually, my scripts doesn’t work really good ; it seems the ball do not collide with my character ( The character climb on the ball and nothing happens, the ball move a little bit on the side but nothing else). Have you an idea of what to do ?

  • Liked by
Reply
Cancel