Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 RanecSlof · Nov 15, 2016 at 10:35 AM · c#raycastcollider

[c#] Hit a object and shoot it away with raycast?

I need help with my script.( I am a beginner in scripting) What I want is that i can shoot a Bal away when i collide it whit my driving car. The problem i got now it doesnt shoot away It doesnt matter how much is set the relative force it isnt going fast. Also it doesnt go the right direction i want it to go.
I have search something about raycast and that should be the best solution but i dont know anything about raycast. Anyone here that can help me out ?

This is the code i'm using atm.

  using UnityEngine;
     using System.Collections;
     
     public class BallPush : MonoBehaviour 
     {
         
         void OnTriggerEnter(Collider otherObject) 
         {
             if (otherObject.gameObject.name == "bal") 
             {
                 otherObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * 10000);
             
                 //otherObject.GetComponent <Rigidbody> ().AddRelativeForce (new Vector3 (1000, 1000, 0)); 
             }
             //print(otherObject.gameObject.name);
         }
     }



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 ThePersister · Nov 15, 2016 at 11:34 AM

Heey there @RanecSlof,

I set up a little example scene for you to mess around in, check out the Ball and the Player. https://www.dropbox.com/s/gig63ycufhsyvnk/PlayerPushBall.unitypackage?dl=0

Here's the specific code you asked for, explained below:

 using UnityEngine;
 using System.Collections;
 
 public class PushOnCollision : MonoBehaviour
 {
     public float m_pushStrength = 20f;
 
     void OnCollisionEnter( Collision coll )
     {
         Rigidbody otherRigidbody = coll.rigidbody;
         if( otherRigidbody != null && otherRigidbody.gameObject.tag == "Ball" )
         {
             Debug.Log( "Hit the Ball" );
             Vector3 impactPoint = coll.contacts[ 0 ].point;
             Vector3 direction = otherRigidbody.position - impactPoint; // from point of impact to Center of target
             direction.Normalize();
             
             // Draws a line and that sticks around for 3 seconds.
             Debug.DrawRay( impactPoint, direction * 5f, Color.magenta, 3f );
 
             otherRigidbody.AddForce( direction * m_pushStrength, ForceMode.Impulse );
         }
     }
 }

  1. I chose to use OnCollisionEnter, instead of OnTriggerEnter, since collision is what you want, triggers are often used for Zones, DoorTriggers, Traps and the like.

  2. I used ForceMode.Impulse as the 2nd argument for AddForce, that way, the speed is applied as if fired by a cannon, without it, it's like pressing down the pedal of an Ultra Fast Car for a fraction of a second, which doesn't amount to it starting to move very quickly, that's because the default mode is Acceleration.

  3. Instead of using RelativeForce, I calculated the direction between the point of impact and the center of the ball, make sure NOT to use RelativeForce and this direction combined, as that will lead to weird behaviour.

  4. I draw a ray so you can see in your Scene View whether the applied force's direction is correct or not.

  5. Instead of name checking, I added a Tag to the "Ball" and checked for that instead of per name basis, which is more dangerous.

(I could further advise creating a Ball script (doesn't matter if it's empty), adding that to the ball, and checking with GetComponent(), that's the safest and cleanest way to actually do it.)

I hope that gets you up to speed! Best of luck developing your game :)

If this helped, please accept the answer, I'd appreciate it a lot.

If you need anything else let me know!

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 RanecSlof · Nov 15, 2016 at 12:00 PM 1
Share

@ThePersister Thanks Lex, Works like a charm. It is amazing I appriciate it alot.

Are you joining the Wonder Doctor Game Jam?

$$anonymous$$ind Regards, Ranec

avatar image ThePersister RanecSlof · Nov 15, 2016 at 12:18 PM 0
Share

Hi Ranec, Thanks for accepting, glad I could help! Haven't been checking facebook That much lately, good tip for that new Pillo Game Jam. I'm a bit busy with my graduation internship, but if I have time for it, I'd love to join the Wonder Doctor Game Jam :)

$$anonymous$$ight see you there then, good luck in advance!

avatar image
0

Answer by roman_sedition · Nov 16, 2016 at 05:22 AM

I think the problem with your original script was this line.

  otherObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * 10000);

Vector3.forward is implying that the direction of the force is going up only in the z axis * 10000.

I am thinking what you want is to add force in relation to the car that hit the ball, and the force should be relative to the velocity of the car. I am assuming that this script is on the car, so you could probably use this line of code.

 public void OnCollisionEnter(Collision col)
     {
         if(col.transform.tag == "Ball")
         {
             
             col.transform.gameObject.GetComponent<Rigidbody>().AddRelativeForce(this.transform.GetComponent<Rigidbody>().velocity);
         }
     }
 

But if you literally want to shoot it away you can just change it to this.

 col.transform.gameObject.GetComponent<Rigidbody>().AddRelativeForce(Vector3.Normalize(this.transform.GetComponent<Rigidbody>().velocity) * carForce);
 

Assign whatever crazy number you want carForce to be.

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

6 People are following this question.

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

Related Questions

Smooth Movement on Geometry Collission? 0 Answers

Can't get a laser working properly. 2 Answers

Raycast not working on object without gravity 0 Answers

Distribute terrain in zones 3 Answers

(C#) Collider to collider2d 0 Answers


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