- Home /
Raycast on ball game
Hi everyone! I'm having some problems with physics on my project. When a ball collides with a collider or other ball in a considerable speed, both balls get the inverse direction (thats right). But, if one ball is too slow, the faster one, hits and takes the inverse direction, but the one which was slow, continues slowing down due to friccion on ground. I want to at every collision the balls get some speed boost in the inverse direction. I think you understand... (my english is sooooooooo bad :( ) Here's the code:
using UnityEngine;
using System.Collections;
public class ballControl : MonoBehaviour {
Rigidbody myRigidbody;
Vector3 oldVel;
void Start () {
myRigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate() {
oldVel = myRigidbody.velocity;
}
void OnCollisionEnter (Collision c) {
ContactPoint cp = c.contacts[0];
// calculate with addition of normal vector
myRigidbody.velocity = oldVel + cp.normal*1.0f*oldVel.magnitude;
// calculate with Vector3.Reflect
myRigidbody.velocity = Vector3.Reflect(oldVel,cp.normal);
// bumper effect to speed up ball
myRigidbody.velocity += cp.normal*1.0f;
}
}
Answer by Habitablaba · Oct 09, 2014 at 09:00 PM
// calculate with addition of normal vector
myRigidbody.velocity = oldVel + cp.normal*1.0f*oldVel.magnitude;
You don't need to multiply by 1.0f here, that does nothing.
Do you mean to be multiplying by oldVel.magnitude here? Since you're not normalizing oldVel, it still contains the direction and magnitude data. This means you're essentially squaring it. This would be a big reason one object is shooting off and the other is not.
If you are looking for them to both shoot off at the same speed, you'll need to do some maths to transfer momentum from one object to the other.
Wasn't exaclty what im looking for, but worked. Thanks again. I have one last problem, wanna help? <3
Answer by dmg0600 · Oct 09, 2014 at 03:59 PM
Where is the raycast part of your problem? Please construct your question according to your problem.
If the ball is stopped or moving really slowly at the time of the impact it most certainly won't react as its rigidbody will be asleep and won't recieve any callback.
If you want an asleeped rigidbody to react to OnCollisionEnter you can wake it up every frame although it might be costly in performance. Use rigidbody.WakeUp() for this.
You can read about sleeping rigidbodies in the documentation.