- Home /
2D - Locking The Z Axis
So, I'm making a 2D Platformer. I've been able to add some nifty features, but lately I've run into a problem. I would like my character to only move on the X and Y axis without any movement in the Z axis. Everytime I collide with a box, my character falls off the platform on the Z axis which I don't want. I've heard about configurable joints, but I'm still unclear about this all.
Thanks In Advance
Answer by Peter G · Jun 26, 2010 at 01:55 PM
This question has been answered in multiple places before. There are 2 common solutions. One, in your player code, every frame call:
//JS
function Update () {
transform.position.z = 0;
}
//C#
//using UnityEngine... public class...
void Update () {
Vector3 pos = transform.position;
pos.z = 0;
transform.position = pos;
}
or you can add a configurable joint. Then go to z motion and choose locked instead of free or limited.
Other links.
@Peter G, one $$anonymous$$or point - that's Javascript. In C# you can't assign to Z, you have to do: transform.position = new Vector3(x, y, 0)
Right, I'll post the C# version. $$anonymous$$ost newcomers seem to choose JS because all the documentation is JS so I write it as such.
@Peter G, true, I wasn't suggesting you change the post, I figured anyone seeing the post would also see my comment, which would be enough notice. :)
The C# script completely froze my character so that it wouldn't move in any direction. Anyone know why? I created a C# script with only the contents above and attached it to my gameObject (character controller).
Answer by DragonGamingYT · Jul 17, 2016 at 07:47 PM
thanks man this helped me so much since my game had a majour bug that made it that if you landed right you'd be sendt off of the map so I had to add barriers but you could use those barriers to jumo infinitely
Answer by Gumpert · Sep 29, 2013 at 06:14 PM
Hi, I'm trying to do a similar thing, but I'm just wondering if its possible to make a script that instead of saying "continuously set z to 0" it would say something like "the z can never change to be anything other than 0 in the first place". Its because if I use this script and I walk into a collider thats facing diagonally (i'm making a 2.5d game, and ill try to not have any diagonal colliders, but it might not be completely possible), you can glitch through it, and it goes all messed up.
I experienced this as well, and it's quite unsatisfactory. I haven't came up with a solution of my own, but I've read that rigidbody components have a mechanism to prevent movement in any of the axes. I'm just not very interested in using one as the games I'm making don't use physics, seems like needless overhead.
I'd love to hear an answer on this topic, anyone out there have a good solution?
Your answer
Follow this Question
Related Questions
Lock Z rotation to 0 2 Answers
Locking the Z-axis based on direction 0 Answers
make object rotate towards its direction after bounce 1 Answer