Author Topic: Do any of you code for your jobs?  (Read 8458 times)

0 Members and 1 Guest are viewing this topic.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #240 on: April 17, 2022, 04:28:57 AM »
Not sure if I wanna touch the platforming corgi engine for this project just because dunno if it'll be compatible with this template. That's more for starting fresh in there.

I feel like this template is a house of cards and I don't want to mess with the internals too much or it'll fall apart and I'm relying on it for player/camera stuff because that saves time.

Maybe I'll see if I can make the corgi engine character controller mesh with this. Or some of those other ones you mentioned. I don't think the controls are too bad after adjustments. And not trying for a real tight platformer since more interested in a puzzle platformer.


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #241 on: April 17, 2022, 01:55:39 PM »
Also, yeah Sage, this is how movement is handled by the scripts currently. Adjusting RB velocity each update based on movement and movement speed. It doesn't work with conveyer belts because they are trying to move the player but the player velocity is being reset each update to 0 if you're not moving. I wonder if I can add an "if collidingonstay with an object with tag "conveyer" don't update player velocity.

Code: [Select]
private void HandleMovementInput()
    {
        Vector2 movementForce = Vector2.zero;
        if (Mathf.Abs(horizontalMovementInput) > 0 && state != PlayerState.Dead)
        {
            movementForce = transform.right * movementSpeed * horizontalMovementInput;
        }
        MovePlayer(movementForce);
    }

private void MovePlayer(Vector2 movementForce)
    {
        if (grounded && !jumping)
        {
            float horizontalVelocity = movementForce.x;
            float verticalVelocity = 0;
            playerRigidbody.velocity = new Vector2(horizontalVelocity, verticalVelocity);
        }
        else
        {
            float horizontalVelocity = movementForce.x;
            float verticalVelocity = playerRigidbody.velocity.y;
            playerRigidbody.velocity = new Vector2(horizontalVelocity, verticalVelocity);
        }
        if (playerRigidbody.velocity.y > 0)
        {
            foreach (string layerName in passThroughLayers)
            {
                Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer(layerName), true);
            }
        }
        else
        {
            foreach (string layerName in passThroughLayers)
            {
                Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer(layerName), false);
            }
        }
    }


Is there a way that I can tell it to ignore all this and just use default rigidbody built in physics when colliding with an object that is tagged "Conveyer belt"?

I read some threads on kinematic physics for characters and Unitys RB and a lot of people talk about using both and their code switches between the two physics system depending on what the player is doing. Like using RB for moving and then you get hit and it switches on hit to a hand tailored kinematic physics for the knockback force. Or switching to kinematic for climbing ladders/robes and stuff.
« Last Edit: April 17, 2022, 02:00:41 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #242 on: April 17, 2022, 02:26:37 PM »
So yeah, I tried commenting out this bit

" playerRigidbody.velocity = new Vector2(horizontalVelocity, verticalVelocity);"

and dropping my player on the conveyer belt and now it works with moving my player just like moving crates at various speeds.


Problem is, even if I could write some code that said "when colliding with a conveyer belt tag, turn off that one line", now I can't move my player because I removed the velocity entirely and all I can do is move while jumping.

I feel like there has to be a good solution for this that says when colliding with conveyer tag, don't use that line of code, instead use "______" to move left/right?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #243 on: April 17, 2022, 02:46:11 PM »
Lol, when people talk about how long Unity takes to boot I never noticed it with these really small projects I'm working on.

Right now I started a new project to import the Corgi 2d/2.5d platforming engine and it's taking a whiiiile to finish startup.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #244 on: April 17, 2022, 03:16:51 PM »
Wow, this engine within an engine thing is insane.

Like there are so many sample scenes that do a crazy variety of every kind of side scrolling game that exists. It's like it turns Unity into Super Mario Maker. Controls are pretty solid.


For this project there's no reason to use this, any game I made in this Corgi engine wouldn't resemble the base template we're supposed to be modifying at all and the whole assignment is to modify the base template and make a game with it.

But holy hell, after this class is done if I want to try to make some games using pre-made engines, so many possibilities and it's nice having so much done for you already. Like I started designing a prototype for my game and it has water and I'm like "how do I code swimming controls in" whereas this Corgi demo already has swimming in water, ice platforms, ladders, etc....

$30 well spent.

Also if there is stuff like this for every genre to turn Unity into Super Mario Maker of all genres that's crazy and completely changes the idea of game making I had in my head. It does feel like cheating though.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #245 on: April 17, 2022, 03:36:34 PM »
Actually started looking through the editor, like even the most simple stage is very, very complex in these demos. I started going through the scripts in visual basic and this stuff is like 1-2 years beyond me at this point and way over my head.

Basically if I used it would be just using the prefabs with my own art/music/levels and a few adjustments here and there but otherwise wouldn't be messing with the core engine at all because it's way beyond me right now.

Very fascinating and cool learning experience though!

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #246 on: April 17, 2022, 09:45:33 PM »
So, at the end of the day and a lot of excuses and distractions, the truth is I just don't know how to make a fun 2d platformer  :'(


Like you tell me to make a shmup, I just try to make fun & challenging bullet patterns to dodge through with some neat gfx effects, make an adventure game, come up with a story and some dialogue and item based puzzles, horror game, make some spookiness or scares, rpg make a story, some towns/dungeons and a battle system.

But like "place down platforms and dangerous things in a way that is 'fun'" and just...no idea. Same with puzzles. If I make a door that is locked and you have to push a crate on a button, is that fun or is that tedious busywork?


I like the idea behind this class of learning different genre quickly to experiment around, but the class is like "making games should be hard fun" and the first game was, but making games in a genre you don't understand well under a class deadline...just feels like I'm back in school and doing work and getting writer's block and nothing done and taking naps. The class also gives 0 lessons/classes on how to design theory a 2d platformer. It's just generic "watch the making of Uncharted to see how to make characters and story" which doesn't help when designing a Mario level at all.

I still don't have a gameplay loop concept
I still haven't really made a single room
and the game is due in about two weeks.

I can keep watching tutorials and learn how to make more tools and better physics and whatever, but that's just distractions from having no idea how to make fun platforming. Even if I fired up Super Mario Maker 2 I'd have no idea how to make a good level in it.

Doesn't help I only play a sidescrolling platforming game like once every 2-3 years. So yeah I love Celeste/SMB/Hollow Knight/Guacamelee/Cave Story/vvvvv/etc... but those are extremely tight games and the metroidvania ones are BIG games and not the "I'm gonna make this in a weekend as my 2nd game" kind of thing. Not sure what I can get from them.

Plus there's still a lot tech-wise I don't know how to do. I was like "ok, the opening scene will look like this"




And then I'm like here are all the things I don't know how to do to execute that:

Room #2 - Screen shakes
Room #3 - Would want flashing red lights like an alarm, don't know how to do colored lighting
Room #6 - Don't know how to do water motions of something moving in water and not just in a straight waypoint move line, also camera changing tracking to follow robo downstream
Room #7 - Don't know how to do particles to show splash

So yeah, for like the first 20-30 seconds scene it would take me a half-dozen to a dozen hours of learning techniques, which isn't feasible for this.

I need to just make a few simple Mario maker kind of levels that don't require tons of techniques. But just no idea how artistically to design that :| Guess I will keep trying. Also unless I make some fun levels I just don't have the motivation for this project to do my own art/music because it's like what's the point in spending that time on a game I don't even like.

Solution might just be to give up and move to the next class on 3d FPS and come back to trying to do this later after I feel more confident in my design and tech skills.
« Last Edit: April 17, 2022, 09:51:31 PM by Bebpo »

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #247 on: April 18, 2022, 07:43:06 AM »
Problem is, even if I could write some code that said "when colliding with a conveyer belt tag, turn off that one line", now I can't move my player because I removed the velocity entirely and all I can do is move while jumping.

I feel like there has to be a good solution for this that says when colliding with conveyer tag, don't use that line of code, instead use "______" to move left/right?

This is just a maths / physics problem though, right?
You don't actually want to turn off your existing movement, you want to resolve two forces interacting with each other (one 'positive' if youre moving with the conveyor, one 'negative' if you're 'swimming upstream').
So basically, think of this as sideways gravity; how is your current movement controller resolving a gravity constant in the negative Y axis?
Because what you wanna do, is resolve 'sideways gravity' in the X axis, which is probably going to be something like
Code: [Select]
if (col.ground =="conveyor") => rb.setvelocity((input.x * moveSpeed)+conveyor.velocity, rb.velocity.y);

Also if there is stuff like this for every genre to turn Unity into Super Mario Maker of all genres that's crazy and completely changes the idea of game making I had in my head. It does feel like cheating though.

I mean, it's not quite that simple, but most of the decent and well mantained Unity code addons basically give you a new API for doing specific stuff - this is why I suggested you try out that dialogue asset you bought instead of doubling down on getting a VN engine, because I kind of suspect it has everything you need to make a VN built in.

The upside is to get something done, you're working like you'd be working at an actual games company where someone else is doing the engine work to enable the designers / scripters to do what they need to do, which saves you a ton of learning / expertise / time - the downside obviously is if you don't understand something or you get weird bugs, its kind of a black box (although most of the top rated unity addons are really conscientious about customer support and have discords and shit to assist you)

So, at the end of the day and a lot of excuses and distractions, the truth is I just don't know how to make a fun 2d platformer  :'(


Like you tell me to make a shmup, I just try to make fun & challenging bullet patterns to dodge through with some neat gfx effects, make an adventure game, come up with a story and some dialogue and item based puzzles, horror game, make some spookiness or scares, rpg make a story, some towns/dungeons and a battle system.

But like "place down platforms and dangerous things in a way that is 'fun'" and just...no idea. Same with puzzles. If I make a door that is locked and you have to push a crate on a button, is that fun or is that tedious busywork?

Okay, so firstly what I'll say is, if you have no particular love for the genre, don't look at the 'genre kings' which are literally exemplars of platforming methodologies; think back to the 16 bit days, when every fucking movie / toy / cartoon tie in was a sidescrolling platformer. Why? Because if you have a decent character controller, moving around in a 2D space is pleasing, and you then just have to tell a visual story (based on the IP) so the player wants to keep playing to see what the next area is going to be.
Chuck in a boss fight every 4 levels, and you're gold. Throw in some collectibles hidden around and you have replayability.
Don't overthink it.

HAVING SAID THAT; you don't even have to make a 'platformer' game - play something like Lost Vikings or Krustys Funhouse; these look and feel like platform games, but they're fucking not.
Look at Zelda 2, or more recently things like Mark Of The Ninja, or Fez.
If you know how to build a satisfying SHMUP, go ahead and build that; you're just adding an additional play constraint of gravity. Hell, thats basically Contra, right?

And then I'm like here are all the things I don't know how to do to execute that:

Room #2 - Screen shakes
Room #3 - Would want flashing red lights like an alarm, don't know how to do colored lighting
Room #6 - Don't know how to do water motions of something moving in water and not just in a straight waypoint move line, also camera changing tracking to follow robo downstream
Room #7 - Don't know how to do particles to show splash

Screenshakes = easy; you already know how to find your camera, just fuck with its transform for a second then reset it (might want to use a Tween library to do this though to get a nice easing)
Flashing lights = also easy; when you add a light, you can literally colour it in the inspector. If you're using the URP there's a nice suite of specific 2D lights built riht into unity too. Otherwise, just drop a spotlight in at a z position so you can aim it at your scene, and colour it red / set its strength / range.
Water = potentially easy, potentially nearly unsolvable and bringing high end gaming rigs to their knees trying to calculate in real time; think about your end goal, not the 'flavour' or how you might think about implementing it 'correctly' - videogames are all smoke and mirrors, so cheap hacky shit that works and approximates an effect is always going to be usable. If what you want is something that 'wobbles' up and down a little bit deterministically as it moves left and right, just do a SIN wave modifier on your Y position, based on your X position.
Particles = also pretty easy, and also fun to play with, but you might find yourself going down a rabbit hole

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #248 on: April 18, 2022, 07:50:19 AM »
while setting up a little story is important, focus on what would make a fun game first

a big part of what makes levels fun and interesting is having an enemy on the next platform you have to jump to, so you have to time your jump carefully, or perhaps enemy projectiles flying overhead that you have to dodge as you make your jump

think about level layouts, like, would it be fun if you had to search for 5 things in a level to unlock a door to the next level?  so does the player start in the center and have a spoke-design level with 5 discrete challenges in every direction?  or do you go more linear and make the collectibles obvious along the way?

what if you put in a lot of doors/pipes to small bonus room type areas which eventually lead back to the main level?

a common forgiving level design is platforms along a "ground level" which then ascend into a sky area that loops back over the earlier part, so that if you fall you end up in familiar territory and can climb back up

or you reach a tall wall and have to double back up a short climb to get over it

https://vgmaps.com/Atlas/Genesis/Aladdin-Level1-AgrabahMarket.png

I know these are really basic things but if you just make a level with them you can continuously refine it, and opportunities present themselves, "ooh I could put a powerup here, it's a tricky jump off the beaten path"
Uncle

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #249 on: April 18, 2022, 07:56:57 AM »
you can also get a lot of mileage just out of really fucking drilling deep into what a single mechanic can do, and what kind of challenges it can create in mastering that one mechanic.

VVVVVV is a really good example of this, because you can't even jump; the entire game is just pretty much every permutation the maker could come up with of a 'flip gravity' mechanic.

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #250 on: April 18, 2022, 08:18:21 AM »
Monster Party is a very weird NES game that's worth looking into, but one of its main conceits is that the (fairly simple) levels have a lot of doors, some rooms are empty, some have bosses in them who say something weird

https://www.vgmaps.com/Atlas/NES/MonsterParty-Round1.png

you could make an entire game out of that concept, a fairly normal platformer but the fun is coming across a door and thinking oh geeze, what's going to be behind THIS one

actually Kid Icarus was similar to that too, though in that case I think it was more figuring out over multiple playthroughs which rooms are traps that you should avoid?  which is less fun

what about a game where every level has 5 doors, but you can only open 3 of them?  so you want to replay it to see what you missed behind the other doors

are you rescuing hostages and the two you couldn't open are because you were "too late" and those people died?

or is it just a matter of you are given 3 keys in each level and you use them up?

do some have permanent powerups that are missable?

maybe you could even cheat and force the player's third room to be a powerup, no matter what?
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #251 on: April 18, 2022, 07:56:17 PM »
Thanks,

so I made a "real" platforming level with a few things.


You can check it out here:

https://dkclassdesign.itch.io/platformer-room1-test

Let me know what you think. There is:

-Test idea level - Most fun because it has a variety of stuff
-Boring level - Totally rote boring simple level
-Level 2 - mediocre-ish challenge platformer level

All three levels are clearable.

That being said I've decided to throw it all in the fire and start from scratch. No template, no Corgi engine, just new project, make my own character movement, camera movement, game manager, UI manager, use my own art assets from the start for tiles/objects/player.

It's a lot more work, and I honestly don't want to do it while working a full time job (that's a lot of this, there are things I can do to make better quality stuff but I don't want to spend the time/effort. Easier to feel worth spending that time/effort for something that's got initial form going and I'm building on it and excited about what I'm making), but the only way I'll get motivated is if I'm making my own thing and not "making levels/gameplay within someone else's thing".

And like you said, it doesn't need to be a pure platformer. Can be whatever I want. Though honestly the more I work with side scrolling tiles the more I hate making side-scrolling and after this project I'm only doing overhead or 3d games going forward. Filing in tile by tile/platform by platform just feels tedious and boring. Prefer just like painting overhead area all green grass and then individually putting in objects/enemies. Just feels like the environment is much easier to draw out in overhead because you don't have to worry about how the player is getting from every single step to the next.
« Last Edit: April 18, 2022, 08:01:21 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #252 on: April 18, 2022, 09:04:03 PM »
Ok, learning stuff from scratch is pretty helpful. It's nice writing your own movement so you know what is going on the whole time and can adjust it. I'm going through some guides that cover the really basic stuff like this and even for things I know how to use I'm learning a lot of tips. Like I didn't know you could erase tilemaps with shift while drawing titles since in Aesprite it's right click. Also not being tied to an inputmanager someone else has written, so you can just type "getkey or getkeydown" is so nice and refreshing for interactions.

I haven't written any camera script stuff, but how hard is a camera controller that just follows a target's transform position? I think the game manager script will be the toughest bit for me to learn how to make, but conceptually I understand it, so maybe not.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #253 on: April 19, 2022, 06:30:18 AM »
All three levels are clearable.

That being said I've decided to throw it all in the fire and start from scratch. No template, no Corgi engine, just new project, make my own character movement, camera movement, game manager, UI manager, use my own art assets from the start for tiles/objects/player.

theyre all fine, even if I hate those megaman style vanish / reappear blocks :idont

I think there's a lot ot be said for rawdogging your code from complete scrtach though, especially if youre kinda unsure about the specific of what you just done in a tutorial; if nothing else, trying to recreate from memory is going to reinforce learning a lot better than just assuming you have it down.

I haven't written any camera script stuff, but how hard is a camera controller that just follows a target's transform position? I think the game manager script will be the toughest bit for me to learn how to make, but conceptually I understand it, so maybe not.

yeah, ez-mode cam control is just making your camera a child of your player object, intermediate is making an invisible object that moves to your player (or a relative position, if you wanted camera 'leading' like your top down shooter) that the camera focuses on, probably with a smoothdamp or lerp and probably in lateupdate after movements resolved so it doesnt seem jerky.
galaxy brain camera is some kind of box focus so you can move in a genre dependent / relevant area without camera movement until you really need it.

https://www.gamedeveloper.com/design/scroll-back-the-theory-and-practice-of-cameras-in-side-scrollers

some good stuff in there for ideas on camera moves.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #254 on: April 19, 2022, 07:35:55 PM »
Learning so much good code practice going through these tutorials on basic things from scratch. Like how to separate your code so you don't put a ton of stuff in Update but just call methods and put the stuff in that with ///summaries and #region for initial variables to make the script OCD clean to read.

Also learning how and why to make most things private and used [serializefield] instead of public for getting stuff into inspectors but cutting down on bug chances from variables getting messed with outside the script.

This is all stuff the class has basically skipped since it's not really a coding class, but this is so helpful for understanding code and how to write things.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #255 on: April 19, 2022, 09:59:00 PM »
Hey GreatSage, I'm trying to put in conveyors now with my new movement and game from scratch but I'm trying to wrap my head around the coding collision to get a component of the item you've collided with.


This is what I want to do:

Code: [Select]
private void OnTriggerStay2D(Collider2D collision)
    {
        if(collision.CompareTag("Conveyor"))
        {
          private SurfaceEffector2D col;
          col = collision.GetComponent<SurfaceEffector2D>();

          rb.velocity = new Vector2 ((dirX * movementSpeed) + col.velocity, rb.velocity.y);
        }
    }

But this doesn't work because the collider isn't actually bringing you the gameObject you've collided with, just a string with its tag. So when you try to pull a GetComponent of the string it's not going to work.

What do I need to do to pull the SurfaceEffector2d off a colliding object so that I can access it's velocity and add it to my velocity?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #256 on: April 19, 2022, 10:17:06 PM »
Although the more I google this, the more it seems like conveyer belts for characters in 2d games are something that's just inherently a problematic issue in Unity?

https://forum.unity.com/threads/player-controller-unity-2d-character-script-not-working-with-surface-effector-2d.974505/#post-6336327

Basically the info I'm getting is the only way around this is using "addforce" to move and letting the physics determine velocity instead of player controls. This results in slippery physics characters and not tighter 2d controls.

I've googled for days and there's not a single video/website on how to add a simple mario conveyer belt for a 2d game that the player can ride. It's kind of crazy since conveyers are like really basic platforming tools.


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #257 on: April 19, 2022, 10:53:54 PM »
I found this code online and it actually works...mostly, it's good enough that I could use it for certain stuff if I want a conveyer belt. Though to be fair I doubt I'm gonna have any belts in my game at this point and this is more just curiosity trying to figure out how to get past a problem.

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class testbelt : MonoBehaviour
{
// We will need a list of items on the belt. Generic list collections work best for dynamically sizing arrays imo
public List<GameObject> objsOnBelt;
//you can adjust the speed using the float speed. If you want the belt to push right left use a negative number.
public float speed;
// Use this for initialization
void Start()
{
//Best to initialize the list. I find that objects with scripts added dynamically through code don't always intalize lists
objsOnBelt = new List<GameObject>();
}

// Update is called once per frame
void Update()
{
if (objsOnBelt.Count != 0)
{
//We no longer need a bool we can simple see if the list is empty
for (int i = 0; i < objsOnBelt.Count; i++)
{
Debug.Log("MovingPlayer");
objsOnBelt[i].transform.position += transform.right * (speed * Time.deltaTime);
}
}
}
void OnTriggerEnter2D(Collider2D col)
{
//Enter is good for a player detetion because we just need when the player first enters the collider.
// The player will need a rigidbody2d for this detection to work.
if (col.gameObject.tag == "Player" || col.gameObject.tag == "ConveyorObj")
{
// "Player" is a standard tag in the editor you can change your player's tag in the drop down.
// Create a new tag for objects that can react to the conveyor.
Debug.Log("Player in the coveyor");
// Remeber to always delete uncessary debus before building.
objsOnBelt.Add(col.gameObject);
}
}
void OnTriggerExit2D(Collider2D col)
{
if (col.gameObject.tag == "Player" || col.gameObject.tag == "ConveyorObj")
{
// "Player" is a standard tag in the editor you can change your player's tag in the drop down.
Debug.Log("Player left the coveyor");
// Remeber to always delete uncessary debus before building.
objsOnBelt.Remove(col.gameObject);
}
}

It moves the player along the conveyer and if you are jumping against the direction it's pushing you don't jump as far which seem correct, but if you are jumping in the direction it is pushing you don't gain any extra distance/momentum.

Which makes sense because it is just moving your character a frame at a time to the right and not actually adding any velocity. I still wonder if Great Sage's method of adding velocity of an object like a surface effector to the velocity calculating of the player movement would work.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #258 on: April 19, 2022, 11:30:12 PM »
I did a test and I think Great Sage's code will work for velocity.

I basically made a public gameobject on playermovement called "put conveyer object here"
then I dropped it in, grabbed it's 2d surface effector in a variable called suf

Then I just used velocity as (dirX+movement speed) + suf.speed, y)

This seems to work correctly. Harder to jump against it, extra momentum when jumping with it.


So I just need to make an if statement that only applies this when collidingonstay on a conveyer tag object. Because right now with my code if the conveyer speed is 5, you just always have that extra 5 velocity even if not on the conveyer and walking on the ground.

Then I need to figure out a way to grab that surface effector 2d of the object I'm colliding with so I don't do the public thing since I can only drop one belt at a time that way.

That should solve it?

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #259 on: April 19, 2022, 11:45:24 PM »
I like reading your journey into game-making blog even if you don't usually get a lot of varied feedback :mario
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #260 on: April 20, 2022, 12:06:14 AM »
Thanks,

I got the "if on conveyor belt, apply the extra speed to velocity" but, I think there is an inherent issue here. This is my movement code

Code: [Select]
private void UpdateMovement()
    {
       
        dirX = Input.GetAxisRaw("Horizontal");

        if (OnConvey)
        {
            rb.velocity = new Vector2((dirX * movementSpeed) + suf.speed, rb.velocity.y);
        }
        else
        {
            rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
        }
       
        if (Input.GetButtonDown("Jump") && isGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
        }
    }

Its fine when on the conveyor belt, and even fine the first frame you jump, but once it updates to the take frame of your leap you are not on convey and it rewrites your horizontal velocity back to the default velocity. So you don't feel the extra force against or with you when you jump from a conveyor belt.

Conceptually the only way I think you could get around this would be to either:

A) Lock your player's jump in once you leap on the first frame, so you can't adjust any movement mid-air.

B) Somehow tell it to keep running with the conveyor belt speed added to your velocity for an extra second or two? Though if jumps will be different lengths of time I don't see how you could do this without undershooting or overshooting it. Maybe something convoluted like:

If you are on a conveyer belt & if you hit jump, then run coroutine (effected jump)

coroutine effected jump()
Until you collide with non-conveyer belt ground/object
-Keep using x velocity with conveyer belt included
then return

Which at that point should return back to normal velocity movement?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #261 on: April 20, 2022, 12:34:02 AM »
Came up with that coRoutine but it's not working and I know why:

Code: [Select]
  if (OnConvey && Input.GetButtonDown("Jump") && isGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
            StartCoroutine(AffectJump());
        }
        else
        {
            if (Input.GetButtonDown("Jump") && isGrounded())
            {
                rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
            }
        }

Code: [Select]
IEnumerator AffectJump()
    {
        Debug.Log("Is Grounded: " + isGrounded());
        while (!isGrounded())
        {
            Debug.Log("Getting here");
            rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
     
        }
        yield break;
         }

After I jump on a conveyor belt the debug.log still returns "Is grounded = true" so my while loop never runs.

This is because the collider trigger for the ground probably takes a bunch of frames for the jump to initially clear. So yeah when it checks the next frame after starting the jump it thinks it's still colliding with the ground. At least that's my guess.

Not sure what a good way to try to do this is.

*edit* figured out the issue with this one, once in the coroutine or a while loop it never checks isgrounded() again because that's outside the loop/coroutine.
« Last Edit: April 20, 2022, 01:12:53 AM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #262 on: April 20, 2022, 01:11:09 AM »
Spent like the last hour writing various codes attempting to figure out a solution to keep the momentum until contact with a new object but no luck. I think I'll just be happy I have working belts even if they don't affect the jump challenge.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #263 on: April 20, 2022, 10:33:23 AM »
learning how and why to make most things private and used [serializefield] instead of public

👍  :lol

Although the more I google this, the more it seems like conveyer belts for characters in 2d games are something that's just inherently a problematic issue in Unity?

https://forum.unity.com/threads/player-controller-unity-2d-character-script-not-working-with-surface-effector-2d.974505/#post-6336327

I mean... the thing here is, if you read between the lines, the Unity dude is trying to tell them as politely as possible that their code fucking sucks, because if you're using physics you shouldn't be directly applying a velocity (although thats what you commonly see on pseudo-physics based character controllers trying to mimic kinematic 'feel').

Its also not exclusive to Unity, anything using a physics 'system' is going to have the same issues when attempting to reconcile physics with not-physics.

I've googled for days and there's not a single video/website on how to add a simple mario conveyer belt for a 2d game that the player can ride. It's kind of crazy since conveyers are like really basic platforming tools.

yeah, I mean, if nothing else, making your own games gives you a hell of a lot more appreciation for what it takes to make games that feel effortless and basic.
Other platforming shit that will probably surprise you with how much more fucking effort it takes than it seems it should include;
  • One way platforms (can jump through when below, block from above
  • One way platforms you can drop through by pressing down + jump
  • Fucking ladders (!!!)  ???  :lol
  • water you naturally 'float' on, but can also 'swim' around in

Conceptually the only way I think you could get around this would be to either:

A) Lock your player's jump in once you leap on the first frame, so you can't adjust any movement mid-air.

B) Somehow tell it to keep running with the conveyor belt speed added to your velocity for an extra second or two?

Taking it back a step, conceptually what's going on here?
 - You're modifying the players current X velocity via an external system

And what's breaking things?
 - You're directly applying an X velocity (ie effectively zeroing it) on input (which overwrites any modifications)

So an alternative way of doing this would be to not directly apply X-input velocity, but to add X-input velocity after running a check, right?

like
Code: [Select]
player.velocity.X = CheckModifiers(Input.getaxis("Horizontal"));
rb.velocity = Vector2(player.velocity.x, player.velocity.y);

float CheckModifiers(float currentVal)
{
     newval = currentVal;
     //stuff that modifies val
     return(newVal);
}

and if you want a little 'follow through' from being on a conveyor belt, you could think of that as a 'powerup' on 'cooldown', right? So for ~1 sec after jumping, your val is still being modified until the cooldown for that modifier 'wears off', and the 'cooldown' is reset whenever you stand on a conveyor belt, and only starts 'ticking down' when you jump.
You might even want to map cooldown remaining directly to power of modifier too, so you have 'full' power modifier as soon as you jump, after 0.5 secs its only 0.5 power etc

And you're probably thinking "well, that's a lot of fucking legwork just for a conveyor belt", and you'd be right; but what you'll have built is an extensible system that you can 'nicely' modify a players velocity by via coefficients that you can turn on / off and 'cooldown' over time, that you can then use for other stuff, like springboards, 'mud', ice, moonjump power ups etc etc etc that will all work nicely with each other, because they'll all modify X/Y velocities in the same way and can be layered

does that make sense? You seem to have this solution like, 90% figured out by yourself, so I don't wanna be all 'look, just have a fish, bro'

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #264 on: April 20, 2022, 12:04:36 PM »
to be fair 90% of coding is googling what you want to do and finding the fish
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #265 on: April 20, 2022, 12:23:26 PM »
Yeah, I'll take the fish here.

That stuff inside check modifiers is what I spent all night trying to figure out and couldn't get it working. Even using your 1 sec powerup example, I had trouble setting it to continue to add the belt force for 1 sec after jump while on a belt?

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #266 on: April 20, 2022, 01:56:37 PM »
Well I dunno if you really need my fish, after you paid $30 for a create-your-own sushi platter  :lol

but id be thinking of this as something like a general buffs+debuffs timer, its just its a 'mixed' buff/debuff where you're buffed walking right but debuffed walking left (or vice versa)

so something like

Code: [Select]

bool hasEffect;
float moveSpeed=10f;
float conveyorTimer;
float conveyorEffect=5f;

void OnCollisionEnter(col other)
{
     if (other.tag.name=="Conveyor") { ConveyorEffect(100); }
}

void OnCollisionStay(col other)
{
     if (other.tag.name=="Conveyor") { ConveyorEffect(100); }
}

void ConveyorEffect(float duration)
{
     if (!hasEffect) { Invoke("EffectsTimer", 0.1f, 0.1f); hasEffect=true; }
     conveyorTimer=duration;
}

void EffectsTimer()
{
     if(!hasEffect) { CancelInvoke(); return; }
     else
     {
           bool endCheck=false;
           // all your effects checks
           if (conveyorTimer>0) { conveyorTimer-=duration; } else { endCheck=true; }
           if (endcheck) { hasEffect=false; }
     }
}

float GetPlayerXVelocity(float baseline)
{
     playerX = Input.Getaxis("Horizontal") * baseline * Time.deltatime; // or whatever
     if (conveyorTimer>0) { playerX += conveyorEffect; }
     return(playerX);
}

void DoMove()
{
     rb.velocity = Vector2(GetPlayerXVelocity(movespeed), rb.velocity.y);
}


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #267 on: April 20, 2022, 03:05:14 PM »
True, I could fire up the Corgi demo template and look at how their script does stuff for certain objects on the map. Good idea.

So trying to understand your code.

When you collide with the conveyor, the game applies a conveyor effect for 100milliseconds (.1f tick) and as long as you're on the belt it continues to apply that restarting the 100 second count until you exit the collision which is when the 100 millisecond count will actually go down.

The conveyor effect sets the timer as the duration being sent in effect and then invokes a .1 tick rate timer and sets effect as true on character

The timer takes your conveyor time buff duration and then counts it down at a .1 tickrate until it's 0 and then sets endtimer and effect as false.

Player velocity is calculated as normal movement + conveyoreffect as long as the conveyer time is going



Now this clears up an idea I was screwing with for so long last night. That there's no need to tie the conveyor speed buff effect to jumping off the conveyor. I kept trying to make it start upon jump/exiting collision with the belt. By just applying the movement that will continue to apply the force on jump without having to specifically tie it to the jumping command. That's helpful to clear up the logic puzzle I was trying to solve.

So like for the effects check, since different belts may be in the scene at different speeds, how would I get the speed off the conveyor I'm colliding with? That was one of my issues last night and the only "test" get around I had was to make a public gameobject and link a single conveyor belt in as a test so I could grab its speed from getcomponent.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #268 on: April 20, 2022, 03:21:28 PM »
yeah, you got the gist of it; note it might not be the best way, but its how I'd initially approach it while keeping it extensible.

And speaking of extensible, if you wanted another kind of conveyor with a different speed / direction, I can just go ahead that as a new case with a new value, like;
Quote
float GetPlayerXVelocity(float baseline)
{
     playerX = Input.Getaxis("Horizontal") * baseline * Time.deltatime; // or whatever
     if (conveyorTimer>0) { playerX += conveyorEffect; }
     if (conveyorTimer2>0) { playerX += conveyorEffect2; }
     return(playerX);
}

(although a better way would be just having a different mgnitude of effect for different conveyors rather than a new 'class' of conveyor if they do the same thing; maybe making the magnitude of effect be attached to the conveyor script, and then deriving it from there on collision contact)

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #269 on: April 20, 2022, 03:31:24 PM »
Ok, just spent like 30 mins integrating this into my player movement existing code base. But it's not getting to the point of effects. Going to debug each step and trying to figure it out.

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #270 on: April 20, 2022, 03:35:52 PM »
just design the game in such a way that all conveyors are located at y = 50 and then if the player's y is ever 50 set their X velocity to -10

:idont  :whatisthis
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #271 on: April 20, 2022, 03:38:12 PM »
I guess this is my first time using oncollision instead of ontrigger.

It was giving me a red flag on other.tag.name, so I tried using other.tag which worked for trigger but doesn't work for collision?

 void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log("Test2");
        if (other.tag.name == "Conveyor") { ConveyorEffect(100); }
    }

The bold is giving me:

Collision2D does not have a definition for tag.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #272 on: April 20, 2022, 03:41:10 PM »
Fixed it

if (other.gameObject.CompareTag("Conveyor")) { ConveyorEffect(100);

But now my player is moving with 5f even when not on the conveyer and on the ground lol, time to figure out what is wrong.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #273 on: April 20, 2022, 03:56:32 PM »
Nm,

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #274 on: April 20, 2022, 04:04:31 PM »
Basically among the few issues I'm having is the timer/effect isn't actually working

Code: [Select]
   void ConveyorEffect(float duration)
    {
        Debug.Log("Getting Here4");
        if (!hasEffect) { Invoke("EffectsTimer", 0.1f); hasEffect = true; }
        conveyorTimer = duration;
    }

    void EffectsTimer()
    {
        if (!hasEffect) { CancelInvoke(); return; }
        else
        {
            Debug.Log("Getting Here5");
            bool endCheck = false;

            // all your effects checks
            if (conveyorTimer > 0) { Debug.Log("Getting Here6"); conveyorTimer -= duration; }
            else { Debug.Log("Getting Here7"); endCheck = true; }
            if (endCheck) { Debug.Log("Getting Here8"); hasEffect = false; }
        }
    }

It's getting to 6, but never hits 7/8 so it never turns endCheck to true.

I can't tell if this is because the timer is only running 1 time and timer is > 0 so it say 100-.1 = 99.9 and then it never runs timer again? I tried changing the timer to a while loop and it just crashed the whole thing.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #275 on: April 20, 2022, 04:08:12 PM »
Actually I see the error. It was giving me an issue in compiler on the invoke having .1f, .1f and told me it should only have a string + one float so I changed it and it was happy. I guess it needs both to keep repeating. Just need to figure out the language the compiler will like.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #276 on: April 20, 2022, 04:10:29 PM »
Nah, it could just be me misremembering parameters - my code snippets are being written with Simpleforums as my Syntax Hightlighting  :lol

I might have just forgotten / confused Invoke withInvokeRepeating

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #277 on: April 20, 2022, 04:13:19 PM »
Yeah that's what I thought but Invoke Repeating is still giving me compiler issues?
This is the timer you gave me in the other project which worked fine:

InvokeRepeating("MyTimer3", 0, tickrate);

But here it tells me this is bad:

InvokeRepeating("EffectsTimer", .1f, .1f);

The error says:
There is no argument given that corresponds to the required formal parameter 'repeatRate' or 'Monobehaviour.InvokeRpeating(string, float, float)'

I get the same error whether it's Invoke or InvokeRepeating.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #278 on: April 20, 2022, 04:15:28 PM »
actually changing it to 0 like the other one fixes the error, let me see if it works now.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #279 on: April 20, 2022, 04:16:38 PM »
It compiles and runs but still not getting the "getting here 7" meaning the timer is never = or <0 even when off the belt.

Also I put conveyorTimer in update and yeah it goes to 100 when jumping on the belt but never goes down from 100.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #280 on: April 20, 2022, 04:21:55 PM »
It compiles and runs but still not getting the "getting here 7" meaning the timer is never = or <0 even when off the belt.

this:
Quote
if (conveyorTimer > 0) { Debug.Log("Getting Here6"); conveyorTimer -= duration; }
should probably be
Code: [Select]
if (conveyorTimer > 0) { conveyorTimer -= 1; Debug.Log("Getting Here6, and timer is: " + conveyorTimer); }
for a) non-fucked up code  :lol (its late and I'm doing this from memory) and b) more info on your debugging - I wouldn't be surprised if conveyortimer was never decreasing because duration was never set, and I dunno why I had that in my OG code in the first place looking back at it  :lol

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #281 on: April 20, 2022, 04:23:48 PM »
Fixed it this way which seems to work?

In your code it's set as duration
conveyorTimer = duration;

instead I tried

 if (conveyorTimer > .1) { Debug.Log("Getting Here6");
                conveyorTimer--; }

And it counts down now and gets to 7/8. Let me try adding the movement effect now and see if it works.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #282 on: April 20, 2022, 04:32:12 PM »
OK, got it working. Had to set the timer on 10 otherwise would keep moving the player after they land and are walking on the ground. 10 seems to run out before they land.

Here is my player movement code at this point
Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    #region Variables
    private Rigidbody2D rb;
    private SpriteRenderer sprite;
    private BoxCollider2D coll;
    private Animator anim;
    private float dirX = 0f;
    bool hasEffect;
    float conveyorTimer;
    float conveyorEffect = 5f;
    float duration;


    [SerializeField] private LayerMask jumpableGround;

    // Gets movement speed & jump strength

    [SerializeField] private float movementSpeed = 7f;
    [SerializeField] private float jumpStrength = 14f;

    public GameObject Convey = null;
    private SurfaceEffector2D suf;

    private enum MovementState { idle, running, jumping, falling }
    private MovementState state = MovementState.idle;
    #endregion


    /// <summary>
    ///  Gets and assigns the rigidbody, animator and sprite to local variables
    /// </summary>
    private void Start()
    {
        Debug.Log("Start");
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        sprite = GetComponent<SpriteRenderer>();
        coll = GetComponent<BoxCollider2D>();
        if (Convey != null) {
        suf = Convey.GetComponent<SurfaceEffector2D>();
        }

    }

    /// <summary>
    /// Updates Movement & Animation State
    /// </summary>
    private void Update()
    {
        UpdateMovement();
        UpdateAnimationState();
        Debug.Log("Conveyor Time: " + conveyorTimer);
    }

    /// <summary>
    /// Gets horizontal axis movement and applies it with movement speed to be the new x-axis velocity
    /// Gets jump and assigns y-axis velocity based on jump strength while still using existing movement speed from last frame
    /// </summary>
    private void UpdateMovement()
    {
        GetPlayerXVelocity();
        rb.velocity = new Vector2(dirX, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && isGrounded())
        {
           rb.velocity = new Vector2(rb.velocity.x, jumpStrength);
        }
    }

    float GetPlayerXVelocity()
    {
        dirX = Input.GetAxisRaw("Horizontal") * movementSpeed;
        if (conveyorTimer > 0) { dirX += conveyorEffect; }
        return (dirX);
    }

    /// <summary>
    ///  Updates animation based on if running or idle and flips sprite based on horizontal direction
    /// </summary>
    private void UpdateAnimationState()
    {
        MovementState state;

        if (dirX > 0f)
        {
            state = MovementState.running;
            sprite.flipX = false;
        }
        else if (dirX < 0)
        {
            state = MovementState.running;
            sprite.flipX = true;
        }
        else
        {
            state = MovementState.idle; ;
        }

        if (rb.velocity.y > .1f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < -.1f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("State", (int)state);
    }

    /// <summary>
    /// Does Boxcast .1f down and returns true or false if overlapping jumpableGround layer
    /// </summary>
    /// <returns></returns>
    private bool isGrounded()
    {
        return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
    }


    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Conveyer")) { Debug.Log("Starting Conveyer Effect"); ConveyorEffect(10); }
        else conveyorEffect = 0f;
    }

    void OnCollisionStay2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Conveyer")) { ConveyorEffect(10); }
        else conveyorEffect = 0f;
    }
    void ConveyorEffect(float duration)
    {
       
        Debug.Log("Getting Here4");
        if (!hasEffect)
        { InvokeRepeating("EffectsTimer", 0, .1f);
        hasEffect = true;
        }
        conveyorTimer = duration;

    }

    void EffectsTimer()
    {
        if (!hasEffect) { CancelInvoke(); return; }
        else
        {
            Debug.Log("Getting Here5");
            bool endCheck = false;

            // all your effects checks
            if (conveyorTimer > 0) { Debug.Log("Getting Here6");
                conveyorTimer--;
                conveyorEffect = 5;
            }
            else { Debug.Log("Getting Here7"); endCheck = true; }
            if (endCheck) { Debug.Log("Getting Here8"); hasEffect = false; conveyorEffect = 0; }
        }
    }

}


Now, after all this there's still one inherent issue even if I could figure out a way to grab the conveyor belt speeds of each belt and adjust the conveyorEffect off their speed in 2dsurfaceeffector.

When I jump against the belt it's tougher because of the force = good
When I jump with the belt I get extra distance because of the force = good
When I'm on the belt I get pushed in the direction = good
When I'm off the belt I get normal movement = good

But...when I jump against the belt and turn in mid-air towards the belt I go flying that way.

Basically the way this code works would be perfect for a wind stage. Forget the belt thing, just have this extra force always applied and bam you have every wind stage ever in a 2d platformer.

But it's not quite right for jumping from conveyor belts. Not sure if there's a solution to this, at this point I'm just not planning on having belts or if I do they are setup in a way that locks the player from jumping in the first place and just moves the player around along with crates/other objects.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #283 on: April 20, 2022, 04:38:28 PM »
Also when you fall right off the conveyor belt to the ground at 10 you still bobble a few steps before stopping. Not sure if there's an easy way to just tell it to stop once it touches ground. I thought my

"void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Conveyer")) { Debug.Log("Starting Conveyer Effect"); ConveyorEffect(7); }
        else {conveyorEffect = 0f;}
    }"

Would do that, but it doesn't.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #284 on: April 20, 2022, 04:51:19 PM »
whoops

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #285 on: April 20, 2022, 05:03:55 PM »
I thought I was clever but this doesn't work. It almost works to stop the 2nd issue I mentioned of moving after landing.
Code: [Select]
    void EffectsTimer()
    {
        if (!hasEffect) { CancelInvoke(); return; }
        else
        {
            Debug.Log("Getting Here5");
            bool endCheck = false;
            bool Jumped = false;
            bool Airborne = false;
            bool Landed = false;

            // all your effects checks
            if (conveyorTimer > 0 && !Landed) { Debug.Log("Getting Here6");
                if (rb.velocity.y != 0)
                {
                    Debug.Log("Jumped!");
                    Jumped = true;
                }
                if (Jumped == true && !isGrounded())
                {
                    Debug.Log("Airborne!");
                    Airborne = true;
                    Jumped = false;
                }
                if (isGrounded() && Airborne == true)
                {
                    Debug.Log("Landed!");
                    Landed = true;
                    Airborne = false;
                }
                conveyorEffect = 5;
                conveyorTimer--;
            }
            else { Debug.Log("Getting Here7"); endCheck = true; }
            if (endCheck) { Debug.Log("Getting Here8"); hasEffect = false; conveyorEffect = 0; }
        }
    }

I can get Jumped to debug.log true, airborne to debug.log true, but I can't get landing to connect when I touch ground.

I tried both:

   if (isGrounded() && Airborne == true)
                {
                    Debug.Log("Landed!");
                    Landed = true;
                    Airborne = false;
                }

and in case it was having trouble running IsGrounded I tried

if (Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround) && Airborne == true)

but neither are working to activate landed.

The idea being that once you land on ground it cancels the timer run.

*edit* Also I realized "jumping" is redundant, just need to know when not grounded for airborne and then when grounded for landing which should cover all situations I can think of.

Anyhow, I better get back to work at this point. Will mess with this tonight or just work on my game and leave it alone at this point.
« Last Edit: April 20, 2022, 05:33:01 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #286 on: April 20, 2022, 08:07:19 PM »
Btw, was thinking and similar to the "after airborne if I collide with an object -> cancel momentum timer invoke" idea above,

If you did an "after airborne if getRawInput on horizontal axis and it's in the opposite direction from the direction when I jumped -> cancel momentum timer invoke", that should basically let you control your momentum leap mid-air by pressing back, which seems...ok? And if you're jumping against the momentum you'll just fall down instead of being pushed back with momentum which seems good?

Like I think the only way you could tell it was shakey vs professional is that when you press back to control your mid-air momentum pushed leap forward you'd instantly drop to 0 momentum instead of gradually lessen the momentum by how much you pushed. But that's such a small thing I can live with that.

So basically if I can get both of those timer cancels in, I think it should all work?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #287 on: April 21, 2022, 03:54:17 AM »
So didn't touch that code stuff further but worked on my first level all night and at about halfway just started throwing placeholder art everywhere and designing it all out and finished it.

It's pretty good! I'm very happy with it and it's a good start. Lots of stuff I can clean up and do with the first stage. It's also pretty lengthy. Not sure how that'll work for stuff like Itch.io play in window games if they're actually more than like a 5 min game.

If I stick with this and do a few levels, maybe throw in a boss or two with lifebars, could see this being more like 15-30 mins. Still gotta figure out what I want to do for stage 2.


Also thematically uh, I still need to figure out what my theme is. The first stage is like sorta Swervy MegamanxMarioxNinja? It's just sort of a weird amalgamation of stuff.

I was thinking of that Monster Party game structure that Uncle suggested for level 2, being a bunch of doors that are all mini-level challenges and the bulk of the middle of the game (maybe have like this long level 1, a middle level that's more like a world with doors going into micro-levels each themed on one thing, and then a final stage with a boss or boss rushes or something). And potentially if I go the door route, the doors could be thematically all over the places so the whole thing would feel like a weird PS1/high on drugs game? It might work, or it just feels like a mess of a ton of different styles with no thematic connection and will be terrible lol

But at least I have a solid start now and can just iterate on it. The worst parts of the night (and worst parts of game making in general) is when I get hung up on something really small and stupid and lose an entire hour trying to figure it out. Like I wanted to have signs that you activate by pressing UP. And I figured I'd just use getinputbutton like I do for jump or getrawverticalaxis and if axis goes > .1f or getinputkey("vertical.up") or ("up") or some fucking thing but after an hour of googling and reading documentation I never figured it out how to just check if they are pressing up on a sign. So now the signs just auto play when you stand in them :|

I think one thing that helped motivate me tonight was I watched a video on adding sound effects and so while I was on the unity free asset store getting sfx the tutorial was using I saw a lo-fi BGM pack and the first track fit the stage really well so put that on and was listening to that the whole time I was making and testing it and it clicked a lot better.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #288 on: April 21, 2022, 04:00:18 AM »




Some WIP shots, using placeholder main guy for now and those are placeholder trees until I make some tree tiles


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #289 on: April 21, 2022, 04:52:03 AM »
Actually was going to bed and came up with a story that ties it all together. Pretty much have the whole story penned out now and a general game plan for the rest of the game. Excited to put it together.

The hardest part is just getting to the point where I have a plan. Once I have a plan it stops being bang your head against a wall aimless wasting time and it becomes a fun passion project to make it happen.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #290 on: April 21, 2022, 07:57:28 AM »
When I jump against the belt it's tougher because of the force = good
When I jump with the belt I get extra distance because of the force = good
When I'm on the belt I get pushed in the direction = good
When I'm off the belt I get normal movement = good

But...when I jump against the belt and turn in mid-air towards the belt I go flying that way.

Oh yea, of course, silly me.

Easiest fix would probably be to seperate 'conveyor' effect into 'conveyor left' and 'conveyor right' and add an input check for left/right so going 'with' the flow is additive, and 'against' is subtractive rather than treating it as a generic 'wind boost'.

Other things you might consider - because really, what you're doing here is faking momentum, and momentum doesn't work like wind - is modifying conveyor magnitude by time remaining (so it has 'fall off'); easiest way would be to just use (time remaining / initial time apllied) as a coefficient for a linear drop off, unless you really want to get fancy.

Btw, was thinking and similar to the "after airborne if I collide with an object -> cancel momentum timer invoke" idea above,

If you did an "after airborne if getRawInput on horizontal axis and it's in the opposite direction from the direction when I jumped -> cancel momentum timer invoke", that should basically let you control your momentum leap mid-air by pressing back, which seems...ok? And if you're jumping against the momentum you'll just fall down instead of being pushed back with momentum which seems good?

...and this was gonna be my other suggestion, that you zero out the 'boost' with a 'counter' move in the opposite direction. This is (obviously) unrealistic as fuck, but then so is platformer air control in general.
What it might do though is open up an interesting mechanic where you have to avoid 'overshoots' by using air control momentum damping for precision landing.

For the 'still has some momentum after leaving a conveyor without jumping' thing, presumably your grounded check has an if (floortag=conveyor) { doconveyorstuff(); } check? because you can zero out any conveyor stuff if grounded and not on a conveyor pretty safely I'd think, as that's basically how friction works anyway.

It's pretty good! I'm very happy with it and it's a good start. Lots of stuff I can clean up and do with the first stage. It's also pretty lengthy. Not sure how that'll work for stuff like Itch.io play in window games if they're actually more than like a 5 min game.

Have a look at playerpreferences (which I think work in WebGL builds) and give players a stage select / save stages cleared functionality and they'll be fine I reckon; I mean, shit, that's more accomodating of a users time than a lot of actual commercially released NES titles did  :lol

Like I wanted to have signs that you activate by pressing UP. And I figured I'd just use getinputbutton like I do for jump or getrawverticalaxis and if axis goes > .1f or getinputkey("vertical.up") or ("up") or some fucking thing but after an hour of googling and reading documentation I never figured it out how to just check if they are pressing up on a sign. So now the signs just auto play when you stand in them :|

You could modify my generic trigger script with an extra control check to do this, and then just enable / disable the textbox on trigger enter / exit?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #291 on: April 21, 2022, 11:39:04 AM »
For that last bit, I mean, after an hour of research, I still couldn't figure out what the "up button" is literally called. My code works with any other button since I can get the "e" key or "jump" button, but under inputmanager there is no up, only "Vertical" positive and I can't figure out the name. "Vertical.positive" or "Vertical > 0" aren't it.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #292 on: April 21, 2022, 12:27:42 PM »
it'll be something like
Code: [Select]
if (input.getaxisraw("Vertical") > 0)

I'm pretty sure; might be easier to do a button check anyway though? (IIRC SMW does the infoboxes with jump)

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #293 on: April 21, 2022, 12:31:06 PM »
it'll be something like
Code: [Select]
if (input.getaxisraw("Vertical") > 0)

I tried that one actually haha, it didn't work. Was really buggy.

Quote
I'm pretty sure; might be easier to do a button check anyway though? (IIRC SMW does the infoboxes with jump)

but then you'd have to tell it to not jump when in a sign trigger zone which is workable but idk if it'll feel bad.

The main reason I don't just use E or something for interact button is I want it to be controller friendly.


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #294 on: April 21, 2022, 12:37:16 PM »
Also, now that I'm at a computer.

Quote
For the 'still has some momentum after leaving a conveyor without jumping' thing, presumably your grounded check has an if (floortag=conveyor) { doconveyorstuff(); } check? because you can zero out any conveyor stuff if grounded and not on a conveyor pretty safely I'd think, as that's basically how friction works anyway.

Right now it's on a collision, if collider tag.

You're right that it might be better to switch it to the ground check. Might fix some of this stuff.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #295 on: April 21, 2022, 01:22:04 PM »
So I switched the conveyor to a layer mask ground but I still can't reach landed = true.

Any idea why?

Code: [Select]
private bool isConveyor()
    {
        return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, Convey);
        Debug.Log("OnConvey");
    }

Code: [Select]
  private bool isGrounded()
    {
        return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
    }

Code: [Select]
if (isGrounded() && !isConveyor())
        { conveyorEffect = 0; }

        if (isGrounded() && isConveyor())
        { ConveyorEffect(20); }
Code: [Select]
void EffectsTimer()
    {
        if (!hasEffect) { CancelInvoke(); return; }
        else
        {
            Debug.Log("Getting Here5");
            bool endCheck = false;
            bool Airborne = false;
            bool Landed = false;

            // all your effects checks
            if (conveyorTimer > 0 && !Landed)
            {
                Debug.Log("Getting Here6");
                if (!isGrounded())
                {
                    Debug.Log("Airborne!");
                    Airborne = true;
                }
                if (isGrounded() && Airborne && !isConveyor())
                {
                    Debug.Log("Landed!");
                    Landed = true;
                    Airborne = false;
                }
                conveyorEffect = 5;
                conveyorTimer--;
            }
            else
            {
                conveyorTimer = 0;
                conveyorEffect = 0;
                Debug.Log("Getting Here7"); endCheck = true;
            }
       
            if (endCheck) { Debug.Log("Getting Here8"); hasEffect = false; conveyorEffect = 0; }
        }
    }

I mean logically, if I'm getting to "Airborne" debug.log it means I'm not Grounded and Airborne = true, so when I land I should be Grounded = true & Airborne variable still = true and "Landed!" should trigger? but it's not?

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #296 on: April 21, 2022, 01:36:42 PM »
(Image removed from quote.)

(Image removed from quote.)

Some WIP shots, using placeholder main guy for now and those are placeholder trees until I make some tree tiles

visually what you did with some of those platforms reminds me of techniques used in certain games like Castlevania 3 to show an under-shadow below blocks that are sticking out into the foreground



I know that's not the intent since it's not under all of them, just a thought
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #297 on: April 21, 2022, 02:09:26 PM »
So I got the conveyor belt working finally. I used visual basic's suggestions because for whatever reason it kept greying out the bool Airborne and telling me that

"setting the bool Airborne = true when you've taken to the air is redundant"

And sure enough I checked if Airborne was actually being set as true and it wasn't. I have no fucking idea why.

Code: [Select]
if (!isGrounded())
                {
                    Debug.Log("Airborne!");
                    Airborne = true;
                }

The debug.log would run, but the bool which was created at the start of the timer as private bool Airborne = false; would not be set true. This is weird as fuck. The other bools were fine.


So I rewrote the code in that section without Airborne bool to

Code: [Select]
void EffectsTimer()
    {
        if (!hasEffect) { CancelInvoke(); return; }
        else
        {
           
            bool endCheck = false;
            bool Landed = false;

            if (isGrounded() && !isConveyor())
            {
                Debug.Log("Landed!");
                Landed = true;
       
            }

            if (conveyorTimer > 0 && !Landed)
            {
             
                if (!isGrounded())
                {
                    Debug.Log("Airborne!");
                }

                conveyorEffect = 5;
                conveyorTimer--;
            }
            else
            {
                conveyorTimer = 0;
                conveyorEffect = 0;
                endCheck = true;
            }
       
            if (endCheck) { hasEffect = false; conveyorEffect = 0; }
        }
    }

Now it says landed when you touch ground that isn't a conveyor belt. And it turns off the effect timer. So you get momentum going into your jump but not continuing after you land.

I guess I'll fuck with the left/right to cancel momentum timer next. If I get that then I'm making AN ENTIRE ROOM OF NOTHING BUT CONVEYOR BELT PLATFORMING in order to justify all this time spent on this logic problem.


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #298 on: April 21, 2022, 02:34:19 PM »
Ok, got it. Even fine tuned it so if you let go of holding left when jumping against a belt moving right the 0 input will have you fall straight down instead of at a wind push angle to the right. Whereas if you jump with the momentum to the right and press nothing you'll keep going with the momentum and it'll only cancel on landing.

Will make a variable for beltDirectionRight? and flip the code if it's going left (as well as using that variable to flip the effect momentum).

Between those and a [serializefield] variable for belt speed that basically should do it for conveyor belts.

Though I'm not suuuper thrilled that the belt speed is determined on the player beforehand vs a way to grab a variable of speed off each individual belt with a script that can be set with its own speed & direction. Basically the current way I'll have to use tags for BeltRight, BeltLeft along with the Conveyor layer mask to tell the player movement script which way to go on them and if I want to set multiple speeds for the belts in one room I'd need to tag them BeltLeft2/3/etc... and write in the player script the speed for each tag.

There has to be a way to get something besides a tag/masklayer from the object you collide/trigger with, right?? All I need is some way to call GetComponent of what I'm colliding with and I can put the speed/direction stuff in those belts and pull them with my character on collision.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #299 on: April 21, 2022, 03:11:27 PM »
also a really minor polish thing that logically I'm trying to figure out as the final touch before I load a room with conveyor belts.

If you are jumping against the belt momentum (i.e. belt is going right and you jump left), if you let go of the controller your character falls flat (ok)

but their sprite still flips the other direction like you pressed back. I.e. your sprite is facing left as you push against the belt, you jump left and it's still facing jump left and you let go and now it's facing jump right as it falls flat. This doesn't happen in the other direction because I'm not cancelling momentum with 0, you actually have to press back to cancel momentum if you're jumping with the belt direction.

Logically, cancelling momentum with 0 but for an extra frame update it sees that as being less than dirX was on the previous frame so it flips the sprite.

Trying to think of a logic solution to this.

Maybe something convoluted in the animation bit like:

IF (special 0 fall from belt jump && if notgrounded && if getrawinput axis horizontal = 0)
then do nothing
Else - update animationstate

which might cover the fall and if you press back it would skip that and update animation and if you touch ground it'll update animation (which still could potentially flip the sprite direction on landing depending on what the dirX it's comparing to is at the landing moment).
« Last Edit: April 21, 2022, 03:17:14 PM by Bebpo »