[HELP]Scripting, box collider and rigidbody

Hi there! My name is Alexis and i’m from Argentina, southamerica, it’s the first time that i post in this forum and it’s because i need a little help. I’m making a script for a 2D sprite player mouvement, i’m using RagePixel for the sprite management, and i have a player with a rigidbody and the “level” with box collider (the floor, walls and roof have their own box collider). The scripts have 2 main problems:

  • the first it’s that when the player try to walk one room to the other, the script play the animation of “falling” (“cayo”) and the method “OnCollisionEnter()” don’t work.
  • the second problem it’s that when the player jumps, sometimes gets an “extra” force that make him jump really high and go throw walls.

I hope some of you can help me, i leave the script and a video with the animation problem.

VIDEO:

SCRIPT:

using UnityEngine;
using System.Collections;

public class Movimiento : MonoBehaviour{

	//Guardar la referencia al componente RagePixelSprite
	private IRagePixel ragePixel;
	
	//Enumerar los estados del personaje
	public enum EstadoDelMovimiento {Parado, CaminarDerecha, CaminarIzquierda, Saltar, Pegar, Cubrir, Nulo=0};

	public EstadoDelMovimiento estadoEjeX = EstadoDelMovimiento.Nulo;
	public EstadoDelMovimiento estadoEjeY = EstadoDelMovimiento.Nulo;
	public EstadoDelMovimiento estadoBoton = EstadoDelMovimiento.Nulo;
	public GameObject bala;
	public float velocidadDeMovimiento = 10f;
	public float velocidadDeSalto = 1000f;
	public float velocidadGravedad = 9.8f;
	public bool tocaAlgo = false;
	public bool armado = false;
	public bool dispara = false;
	public int paraDondeMira = 0; //"0" izquierda, "1" derecha
	public string presionaBotonEjeX = "nada";
	public string presionaBotonEjeY = "nada";
	public string presionaBotonOtro	= "nada";
	public string veoQuePasa = "nada";


	

	void Start(){
		ragePixel = GetComponent<RagePixelSprite>();
	}
	
	void Update (){
		
		Vector3 mover = new Vector3();
		Vector3 gravedad = new Vector3();

		//Indice de Métodos
		//Colisiones: cheque para ver si está tocando algo
		//Verifica si puede saltar
		//Verifica si esta armado
		//Verifica si esta disparando
		//Verifica si Input en el teclado
		//--Verifica Input X
		//--Verifica Input Y
		//--Verifica Input Boton
		//Reproduce las Animaciones
		//Realiza los movimientos
		//Gravedad
		//Crea las cosas extras (Balas, efectos, etc)


		estadoEjeX = verSiHayInputEjeX();
		estadoEjeY = verSiHayInputEjeY();
		estadoBoton = verSiHayInputBoton();
		puedeSaltar ();
		reproducirAnimacion (estadoEjeX, estadoEjeY);
		realizarMovimiento(estadoEjeX,estadoEjeY,estadoBot  on,mover);
		crearExtras();
		//aplicoGravedad(gravedad);
		
	}

	//Chequea si esta tocando algo
	public void OnCollisionEnter()
	{
		tocaAlgo = true;
	}
	
	public void OnCollisionExit()
	{
		tocaAlgo = false;
	}
	//------------------------------


	//Verifica si puede saltar
	bool puedeSaltar()
	{
		//podría poner si esta tocando el piso, pero lo dejo para despues.

		if(estaTocandoAlgo())
		{
			return true;
		}
		else
			return false;
	}
	//------------------------------

	//Verifica si esta tocando algo
	bool estaTocandoAlgo()
	{
		if(this.tocaAlgo)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	//------------------------------

	//Este método devuelve si el personaje esta armado o no
	bool estaArmado()
	{
		if(this.armado)
		{
			return true;
		}
		else
			return false;
	}
	//------------------------------
	
	//Este método devuelve si el personaje esta disparando o no
	bool estaDisparando()
	{
		if(this.dispara)
		{
			return true;
		}
		else
			return false;
	}
	//------------------------------
	
	
	//Verifica si hay algun input para el ejeX
	EstadoDelMovimiento verSiHayInputEjeX()
	{
		if(Input.GetKey(KeyCode.LeftArrow))
		{
			presionaBotonEjeX = "izquierda";
			this.paraDondeMira = 0;
			return EstadoDelMovimiento.CaminarIzquierda;
		}
		else if(Input.GetKey(KeyCode.RightArrow))
		{
			this.paraDondeMira = 1;
			presionaBotonEjeX = "derecha";
			return EstadoDelMovimiento.CaminarDerecha;
		}
		else
		{
			presionaBotonEjeX = "nada";
			return EstadoDelMovimiento.Parado;
		}
	}
	//------------------------------

	//Verifica si hay algun input para el ejeY
	EstadoDelMovimiento verSiHayInputEjeY()
	{
		if(Input.GetKey(KeyCode.UpArrow))
		{
			this.presionaBotonEjeY = "arriba";
			return EstadoDelMovimiento.Saltar;
		}
			this.presionaBotonEjeY = "nada";
			return EstadoDelMovimiento.Nulo;
	}
	//------------------------------

	//Verifica si hay algun input de algun otro boton
	EstadoDelMovimiento verSiHayInputBoton()
	{
		
		if(Input.GetKey(KeyCode.Mouse0))
		{
			presionaBotonOtro = "Mouse0";
			if(this.armado == true)
			{
				this.dispara = true;
			}
			this.armado = true;
			return EstadoDelMovimiento.Nulo;
		}
		else if (Input.GetKey(KeyCode.Mouse1))
		{
			presionaBotonOtro = "mouse1";
			this.armado = false;
			return EstadoDelMovimiento.Nulo;
		}
		else
		{
			return EstadoDelMovimiento.Nulo;
		}
	}
	//------------------------------
	

	//Reproduce la animacion correspondiente según los parametros recibidos
	void reproducirAnimacion(EstadoDelMovimiento ejeX, EstadoDelMovimiento ejeY)
	{
		//Se fija para donde mira
			if(this.paraDondeMira == 0)
			{
				//mira a la izquierda, no flipeo
				ragePixel.SetHorizontalFlip(false);
			}
			else if(this.paraDondeMira == 1)
			{
				//mira a la derecha, flipeo
				ragePixel.SetHorizontalFlip(true);
			}

		
		if(!estaTocandoAlgo())
		{
			ragePixel.PlayNamedAnimation("Cayo",false);
		}
		else if(estaTocandoAlgo()  ejeX == EstadoDelMovimiento.Nulo  ejeY == EstadoDelMovimiento.Nulo)
		{
			ragePixel.PlayNamedAnimation("Parado",false);
		}
		else if(estaTocandoAlgo()  ejeX != EstadoDelMovimiento.Nulo)
		{
			ragePixel.PlayNamedAnimation("Correr",false);
		}

	}
	//------------------------------
	
	//Realiza el movimiento moviendo el sprite
	void realizarMovimiento(EstadoDelMovimiento ejeX, EstadoDelMovimiento ejeY, EstadoDelMovimiento boton, Vector3 mover)
	{
		if(ejeY != EstadoDelMovimiento.Nulo  puedeSaltar())
		{
			mover = new Vector3 (0f,10f,0f);
			transform.Translate(mover * Time.deltaTime * velocidadDeSalto);
		}
		else if(ejeX == EstadoDelMovimiento.CaminarIzquierda)
		{
			mover = new Vector3 (-1f,0f,0f);
			transform.Translate(mover * Time.deltaTime * velocidadDeMovimiento);
		}
		else if(ejeX == EstadoDelMovimiento.CaminarDerecha)
		{
			mover = new Vector3 (1f,0f,0f);
			transform.Translate(mover * Time.deltaTime * velocidadDeMovimiento);
		}
	}
	//------------------------------

	//Este metodo va a crear las cosas extras, como balas, efectos, etc
	void crearExtras()
	{
		if(estaDisparando())
		{
			//Crea nuevo objeto que es la bala
			bala = new GameObject("Bala");
			dispara = false;
		}
	}
	//------------------------------
	
	//Este método le aplica gravedad constante al jugador
	void aplicoGravedad(Vector3 gravedad)
	{
		gravedad = new Vector3 (0f,-2f,0f);
		transform.Translate(gravedad * Time.deltaTime * velocidadGravedad );
	}
	//------------------------------
	
	
	//tengo que hacer un metodo apra que cuando caiga anime la caida
	//tengo que hacer algo ya que si esta cayendo y muevo para el costado pone esa animacion
}

To make OnCollision work you need to define it as:
1.)

void OnCollisionEnter(Collision collision) // You need this argument
{
...
}

2.) You maybe want to use “GetKeyDown” for jumping, if you wan’t it to be the same every time…

Did this help?

Thanks, but the argument of “void OnCollisionEnter(Collision collision)” where do i have to create it ? It has to be like this ? And inside the method ? i just wanted that when the player touch something “tocaAlgo = true”…

public class Movimiento : MonoBehaviour{

public Collision collision;

public void OnCollisionEnter(Collision collision)

    {

        tocaAlgo = true;

    }

}

Thanks a lot IJM i will try both

the collision parameter is passed to the function by the unity engine, if you don’t have the parameter included in your function your collision function won’t be called as it doesn’t match the function definition it’s looking for. You don’t have to do anything with the parameter if you don’t want to.

Unity engine (main loop) is calling that method with the power of Mono framework every time physics engine detects collision; I would recommend you make all call-back methods of MonoBehaviour private, Unity will not have any problems with that, and you would not be able to call them accidentally;
Argument is required, since Unity engine only calls:

everyRigidbidyThatCollided.OnCollisionEnter(collisionDetails); //where collDetails is of the class Collision"

,and can’t identify your method as such;

Thanks both ! ! I will try that and reply here !

The problem of jumping was solve with GetDownKey jump ()

i still have the problem that when moving from one room to another, he is like jumping (one room is clone of the other, the floor is a sprite with BoxCollider). The method I wrote as follows:

//Chequea si esta tocando algo
	public void OnCollisionEnter(Collision collision)
	{
		tocaAlgo = true;
	}
	
	public void OnCollisionExit(Collision collision)
	{
		tocaAlgo = false;
	}
	//-----------------------------

Considering your problem you could use a global variable which raises when you enter a collision and lower if you exit a collision.
If it reaches zero you can set your isTouchingSomething to false.

And a side note, this is from the OnCollisionEnter reference.

So using

void OnCollisionEnter(){

}

should work just as fine.

It work with the global variable ! ! Thanks a lot !