In the game, there is a ball, and moving objects that can hit it. I want the ball to move when an object hits it. But the ball should move to the right direction, the one which the collision was from. I looked for some answers on the internet, however, most codes were in Java script, and those that were in C# weren't helpful because it needed a Rigidbody. The ball is a rigidbody, but the objects that may hit it, aren't. Those are being moved by the CharacterController. The question is how can I detect the collision, to know from what direction it came, and move it to that direction. Thank you.
2 Answers
Use rigidbody.AddForce instead of transform.Translate so that the collisions are detected. For the direction create a variable with the difference between the target and the object itself and then normalize to find out the direction.
-
\$\begingroup\$ Also, using
transform.Translate()
on a Rigibody can slow down your game. It's generally not considered good practice. \$\endgroup\$– Nick B.Commented Aug 6, 2015 at 20:32
I think a normalized vector from the ball to the object.
direction = (ball.transform.position - kicker.transform.position).normalized;
I made a game doing kind of this thing you are doing. (source code link in the post) http://luigigarcia.byethost7.com/projects/goal-a-r-goal/
I think that your kicking object must do this work, not the ball. You need to know the ball someway:
- reference set in some component;
- through the OnCollision MonoBehaviour methods;
- etc..
You apply the direction with something like this:
ball.theRigidbody.AddForce(direction * powerValue);
-
\$\begingroup\$ Thank you @Luigi Garcia But I have a different script for the ball, so how can I get the position of the kicking object? and if I want the ball to move to that direction, how do I use the variable "direction" to do that? \$\endgroup\$ Commented Aug 5, 2015 at 2:38
-
\$\begingroup\$ I think that your kicking object must do this work, not the ball. You need to know the ball someway: - reference set in some component; - through the OnCollision MonoBehaviour methods; - etc.. You apply the direction with something like this: ball.theRigidbody.AddForce(direction * powerValue); \$\endgroup\$ Commented Aug 5, 2015 at 3:03
-
\$\begingroup\$ Can I reference the ball with a rigidbody inside the moving object's script(while it is being moved by the characterController)? \$\endgroup\$ Commented Aug 5, 2015 at 10:31