Reputation: 305
I am trying to create a 2D platformer in Unity. I have made a character in Photoshop and imported him into Unity. I drew a rectangle under him to act as the floor. Then I tried to apply character physics and controllers as per the directions in this video: http://www.youtube.com/watch?v=d3HEFiDFApI. (The two script I used can be found in the description of the video, although I'm pretty sure they're fine, because they work fine for the guy doing the tutorial.)
I then created a new layer called "Collisions", which I applied to the floor and selected in the PlayerPhysics menu. However, when I play the scene, my character just falls right through the floor.
The player controls work - I can move left and right in the air - it just seems to be the physics. When I toggle the physics script off, my player falls to the bottom of my rectangle instead of landing on the top, and it partially covered up, but he can move back and forth. Not sure what the problem is; I would greatly appreciate it if someone could help me out.
Here is the DL link to my malfunctioning project, if anyone wants to take a look at that: http://www.filedropper.com/unityproject
Upvotes: 3
Views: 2045
Reputation: 20038
Looking at your project, the problem is here:
You have set a scale for your player. Your PlayerPhysics (which is based off of Sebastien Lagué's tutorials) does not take that into account.
Your collision detection relies on a set of raycasts which you calculate as follows:
float dir = Mathf.Sign(deltaY);
float x = (p.x + c.x - s.x/2) + s.x/2 * i; // Left, centre and then rightmost point of collider
float y = p.y + c.y + s.y/2 * dir; // Bottom of collider
ray = new Ray(new Vector2(x, y), new Vector2(0,dir));
The problem here is with s
which is defined by
s = collider.size;
You have to remember however that a collider's size values are not affected by the scale. You will have to explicitly adjust for that. Given that your scale in this case has a uniform factor of 0.3, you could do something like
s = collider.size * transform.localScale.x;
But of course you will have to adjust if you have different scaling factors for the different axes. That adjustment should line up the rays just fine.
Perhaps you didn't notice, but in the editor view the rays are drawn when the game is playing. So you can actually get a visual indication of what is going wrong. Make the change described above and all should line up just fine.
Upvotes: 4