Trying to implement basic player movement

Hi,

I am sure this question gets asked a bunch, but I am trying to get some basic player movement implemented into my project. I know there are many tutorials and free code files, but I wanted to try and figure it out on my own since this is the first time I am doing it.

The main issue I am seeing right now is that the player seems to be able to briefly overlap the wall and also sinks into the floor a little. I have a Player GameObject with a RigidBody2D that is Dynamic and currently has Continuous CollisionDetection and Interpolate set to None. This GameObject has a child GameObject for checking if the Player is on the ground. Other than my script, the GroundCheck GameObject has a BoxCollider2D that has IsTrigger set to true and is positioned so that the top is the very bottom of the Player.

Vertically, I first start my game by setting my player to x = 0 y = -3 and immediately upon hitting the play button, the Player’s y value goes to -3.085, as if it’s sinking into the floor a little. For reference, my floor is a Tilemap with a TilemapCollider2D and has IsTrigger set to false.

Horizontally, I am updating the Player with the following

_rigidbody.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * SpeedModifier, _rigidbody.velocity.y);

I am assuming me setting the horizontal velocity manually is what is causing the clipping into the wall? If so, am I supposed to just use AddForce instead for horizontal movement as well? The clipping into the wall is causing my GroundChecker to not work as intended, I think. If I jump into a wall and fall along it while still trying to move into the wall, my current logic thinks the Player is still in the air even after landing, so I can never jump again. To “fix” this, what I did was just making the X size of the collider smaller, but then that seemed to lead into other problems where the player would seem to just get stuck on nothing on the floor sometimes.

For the sake of completion, this is what I do when the player jumps

_rigidbody.AddForce(Vector2.up * Mathf.Sqrt(-2 * JumpHeight * (Physics2D.gravity.y * _rigidbody.gravityScale)), ForceMode2D.Impulse);
_groundChecker.IsGrounded = false;

and the GroundChecker just does this, where the entire tilemap, floor and wall, is tagged with “Ground”

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Ground")
    {
        IsGrounded = true;
    }
}

Sorry if any of this was not clear and any assistance/suggestions are appreciated.

Thanks.

You’re always gonna have a Bad Time™ writing long lines of code like that.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

After it’s all nicely broken out into separate statements…

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

I am actually a software dev by day, so I am more than familiar with the joys of print debugging and used it extensively while building the rest of my project.

I had the realization that I was being stupid and made my player’s collider slightly smaller in order to be more forgiving a few days ago, but I did not realize the other effect this would have because I was not focusing on movement at the time. So, I undid that and now it does not appear to sink into the floor anymore, but as for why an object seemingly placed directly on top of the floor in the editor slightly changes in y upon starting, I do not know and will just accept it as how Unity does physics for the time being. Even now it still goes from y = -3 to immediately -2.985.

On the topic of why my character is seemingly hitting invisible walls while on the floor, that I do not yet know and will just continue to see what I can find. Although, I have a hunch this isn’t something to print debug and is just me using Unity incorrectly somehow.

Moving something in regular frictional contact by setting its velocity is likely going to be a wee bit fiddly.

Even if you set friction to zero, it can still get hung up on lips and ledges and gaps.

You actually CAN move the thing yourself with physics: compute the new position (be sure to use Time.deltaTime in your computations and to do it in FixedUpdate() ) and drive it with rb.MovePosition()

By passing it through MovePosition() (and the new rotation through MoveRotation() ) you can get the full consideration of the physics engine and all callbacks. See blurb below.

Awesome… welcome! I hope Unity brings you as much game-making joy as it has for me.

Still though, unwind your lines. You’ll thank yourself later. :slight_smile: Gamedev is too fluid-and-flexible.


With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.

This means you may not change transform.position, transform.rotation, you may not call transform.Translate(), transform.Rotate() or other such methods, and also transform.localScale is off limits. You also cannot set rigidbody.position or rigidbody.rotation directly. These ALL bypass physics.

Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.

https://discussions.unity.com/t/866410/5

https://discussions.unity.com/t/878046/8

I see. What I was reading up on suggests ghost vertices may be involved, but yea setting velocity manually probably just isn’t the play and I will take the suggestion of using rb.MovePosition() instead. I will also give those threads a read and take the recommendation of unwinding my lines. Thanks.

If you don’t need full physics, this controller is based around the CharacterController Component:

That one has run, walk, jump, slide, crouch… it’s crazy-nutty!!

Pay attention to the differences in callbacks for CharacterController impacts vs Physics.

Wow that is crazy. I will definitely be studying and messing around with that. Thanks!

1 Like

Yeah, jump in man… both feet… don’t be scared of this thing, try everything your developer brain can imagine… and then try some more.

This engine is a BEAST and it can do just about anything if you treat it well. You may actually discover a whole new hobby in Unity3D.