Instead of pulling my hair out and violently hurling things across the room, I thought I’d ask for help from people who know what they’re doing. I’m making a 2D side-scroller, and right now I just have a sprite that can move left and right and the sprite changes when he’s moving left and right along with a rectangle below the player named “Floor”. Floor has a Box Collider 2D on it. The Player has a “Rigidbody 2D” and a “Box Collider 2D” component in addition to the code below.
Jumping does not work at all but the Player does move and animate correctly. He does collide with Floor even though Debug.Log says nothing when he does collide. I’ve been following all of the Unity tutorials and looked at the Unity Scripting References. I’ve searched all up and down these forums and while this came very close to answering my question, I am unlike the user who posted that thread because my object tagged “Floor” is not set as a Trigger.
Here’s the code attached to the Player, but please keep in mind I am really really new to programming in general and I’ve just spent months learning Javascript (I’m specifically having trouble with lines 8-13 and 59-64):
#pragma strict
var speed : float;
var anim : Animator;
var hit : Collision;
var grounded = false;
function OnCollisionEnter(hit : Collision) {
if (hit.gameObject.tag == "Floor") {
grounded = true;
Debug.Log("Shit's hitting");
}
}
function Start () {
anim = gameObject.GetComponent(Animator);
}
function Update () {
//Getting input
var Left = Input.GetKey(KeyCode.LeftArrow);
var Right = Input.GetKey(KeyCode.RightArrow);
var Up = Input.GetKey(KeyCode.UpArrow);
var Down = Input.GetKey(KeyCode.DownArrow);
var Jump = Input.GetKey(KeyCode.Z);
//Commiting speed to sprite animation
anim.SetFloat("Speed", speed);
/*---------------------------------
Horizontal Movement
----------------------------------*/
if (Left) {
if (speed <= 4) {
speed += 0.1;
}
else {
speed += 0;
}
anim.SetInteger("Direction", -1);
transform.Translate(Vector2.right * -speed * Time.deltaTime);
}
else if (Right) {
if (speed <= 4) {
speed += 0.1;
}
else {
speed += 0;
}
anim.SetInteger("Direction", 1);
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
else {
speed = 0;
}
/*-------------------------
Jump
-------------------------*/
if (Jump) {
while (grounded) {
rigidbody2D.AddForce(Vector2.up * 1000);
grounded = false;
}
}
}
I realize there are easier ways of getting horizontal movement by utilizing Input.GetAxis(“Horizontal”) but I feel like it should be within my capability to program for specific buttons if need be. I don’t know. Any help would be greatly appreciated, but please keep in mind you might need to spell seemingly obvious things out for me because I am a sound editor, I studied sound for years and I am not a programmer. Not yet anyway, amiright? :o