- Home /
 
Make the character move a certain direction on collision
Hi there, I am trying to make my character move in the positive y direction when it collides with an object, in this case the wall.
For some reason this does not work at all, even the debug.log doesn't print out. How do I make this work?
I am relatively new to javascript coding and so I'm sorry if it is a really easy thing to fix.
Code sample below:
 function OnCollisionEnter (collision : Collision) {
 if (collision.gameObject.tag == "Wall" && Input.GetKey(KeyCode.LeftControl)) {
             
 Debug.Log("Collided");
 var pushDir = Vector3 (0, 1, 0);
         
 gameObject.rigidbody.velocity = pushDir;
 }
 }
 
              Answer by Stormizin · Sep 04, 2014 at 12:34 PM
Did you attached a Rigidbody to the object that collide with the wall?
The object need a Rigidbody and the wall a collider when both enter in the trigger then the action start.
I tried that, but I can't get the character to move if it has a rigidbody, so I changed the line of code for the direction of movement to: gameObject.transform.forward = pushDir;
But that still doesn't work
Try gameObject.rigidbody.velocity.y = pushDir; With the rigidbody, of course.
Try gameObject.rigidbody.velocity.y = pushDir; With the rigidbody, of course.
@Addyarb, pushDir is of type Vector3, gameObject.rigidbody.velocity.y is of type float, this will end in $$anonymous$$rs.
Answer by Addyarb · Sep 04, 2014 at 08:29 PM
Here you go, it's in C#. I tested with a character that has a rigidbody controller and it works well.
 using UnityEngine;
 using System.Collections;
 
 public class pushBack : MonoBehaviour {
     public int pushDir = 10;
     public int pushBackSpeed = 1;
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
     void OnCollisionEnter (Collision collision) {
         if (collision.gameObject.tag == "Wall" ) {
             
             Debug.Log("Collided");
             
             transform.position = transform.position +
                 transform.forward * -1 * pushBackSpeed;
             //gameObject.rigidbody.velocity.y = pushDir;
         }
     }
 }
 
 
              Just tried this and for some reason it doesn't seem to work
Your answer