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!
↧