Endless Runner Down Movement Not Working

I followed the first episode of blackthornprod’s tutorial on an endless runner. the code looks like this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    private Vector2 targetPos;
    public float Yincrement;

    public float speed;
    public float maxHeight;
    public float minHeight;

   private void Update()
    {

        transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
        {
            targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
      
        } else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight) {

            targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
    
        }
    }
}

The up movement works, but the down doesn’t.

If I remove this:

&& transform.position.y > minHeight

then the down movement starts working again. But that isn’t good, as I have to make sure he doesn’t go past my minHeight.

Those if statements are a bit hairy to look at. They also combine the two conditions in ways that bend my brain.

I recommend maybe reading input, assigning to a temp variable you can inspect, then checking the position separately just to clean up the visuals a bit.

To help gain even 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 are the values of the variables involved? Are they initialized?

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

So in all honesty, im a massive amateur and don’t really get much. Recently I’ve been reading the CS Yellow book, but im still not yet to a point where I learn about stuff like this. So if you could explain to me how to do the temp variable thing? Also wondering if there is another way of blocking the character off of going too high / low.

I don’t find books super helpful. Work through lots of small game tutorials on youtube or Unity learn site. Brackeys on Youtube has great stuff. Steadily improve your ability to grasp what is happening, i.e, don’t just do it like a ritual. Look stuff up in books for sure, but tutorials for small games are a great place to start.

How to break down hairy lines of code:

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

There’s always another way. However your code lines are so long I cannot easily reason about them, so I suggested you take a more one-thing-per-line approach.

And use Debug.Log() on every intermediate step to find out where things go wrong. That’s not a thing someone else can do by staring at your code.