using UnityEngine;
using System.Collections;
public class Ninja : MonoBehaviour {
float speed = 1.0f;
// Use this for initialization
void Start () {
transform.position = new Vector3 (2, 3, -5);
}
// Update is called once per frame
void update () {
}
void faceRight () {
transform.localRotation = Quaternion.Euler (0, 0, 0);
}
void OnCollisionEnter2D(Collision2D coll){
// If the Collider2D component is enabled on the object we collided with.
if (coll.collider == true) {
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
Debug.Log ("Weston sucks eggs");
}
}
}
I’m not an expert, but I think that you need to write your code within the FixedUpdate() method (because its related to physics and you need to test your condition every frame, note just once).
Also, i think you need to get the rigidbody2d component and apply force to it in order to move your gameobject. Something like:
// Declaration
private Rigidbody2D rb;
void Awake()
{
//asign rigidbody2d to the variable rb
rb = getComponent<Rigidbody2d>();
}
void FixedUpdate
{
//apply force to that rigidbody
rb.addforce (vector3/*..... and all sort of parameters you want to apply to it */);
}
I’m maybe wrong because im a complete beginer. Hope it helps though.
As @Cherno said, you need to change OnCollisionEnter2D to OnCollisionStay2D, otherwise you would need to be already providing the input at the instant the object collided, and you would only make a single frame’s worth of movement. Also, there’s no reason to check if the collider is enabled, as you won’t receive the OnCollision message if it’s not.