I am currently working on a 2d platformer. I started by making my level, which consists of several 2d sprites named “platform” (this will become evidently needed later). I then started scripting my character. I ran the code for the first time, and my character moved! Yay! Then it fell through the map. What?
Alright, here’s my characters code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
Transform player;
float playerSpeed;
float jumpSpeed;
float gravity;
private Vector2 moveDirection;
void Start ()
{
player = transform;
playerSpeed = 7.5f;
jumpSpeed = 8.5f;
gravity = 5;
}
void Update ()
{
moveDirection.x = playerSpeed * Time.deltaTime;
if(!isGrounded())
{
moveDirection.y -= gravity * Time.deltaTime;
}
if(Input.GetButtonDown("Jump"))
{
if (isGrounded())
{
movePlayer(Vector2.up * jumpSpeed * Time.deltaTime);
}
}
movePlayer(moveDirection);
}
void movePlayer(Vector2 direction)
{
player.Translate(direction);
}
bool isGrounded()
{
RaycastHit2D hitInfo;
hitInfo = Physics2D.Raycast(player.position, -Vector2.up, 0.01f);
if (hitInfo)
{
if (hitInfo.transform.gameObject.name == "platform")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
As you can see, I didn’t want to use the character controller (I prefer originality). So I check if the character’s grounded using Raycast2D. I believe this is the source of my problem, but I’m not sure. I get no errors from my script at all. I have checked, and the platform sprite is on the same “z” axis as the character’s sprite is. I could use 3D shapes, but that would be un-needed while I’d be in orthographic view for the entire game. Help would be much appreciated, and if you need screenshots just tell me, and I’ll give them up just as soon as I can!
Edit - I am also using Unity 5.1.1F1