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

0 Members and 1 Guest are viewing this topic.

Bebpo

  • Senior Member
Do any of you code for your jobs?
« on: March 23, 2022, 12:36:32 AM »
I'm taking a basic game design intro class and we got to code/writing scripts (C# in Unity) and wondering if anyone here knows like very basic week 1 kind of stuff because some of it is pretty confusing even though I took some C++ classes like 20 years ago and made calculators and basic programs and stuff.

Like I don't understand how to pull an integer variable from one script (i.e. "currentPlayerHealth") and use it in another script in the same game/scene? Like as a test I wanted to write a script that just pulled that value and displayed it in the console log. But when I try to do that it has no idea what currentPlayerHealth is since it's a variable in another script. I feel like this is the most simple 101 stuff since you write modular and keep various pieces in their own scripts.

Gonna be watching lots of youtube tutorials this weekend and trying to write some scripts.

Also another basic example is I have this piece of code on moving a projectile on screen as it updates:
Quote
private void MoveProjectile()
    {
        transform.position = transform.position + transform.up * projectileSpeed * Time.deltaTime;
    }

I understand everything in that sentence except what "transform.up" is doing? It's saying the new position is the old position + speed x time. Which makes sense. I just don't get what transform.up is doing there.

Skullfuckers Anonymous

  • Will hunt bullies for fruit baskets. PM for details.
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #1 on: March 23, 2022, 01:48:29 AM »
Been a few years since I’ve messed with unity so apologies if anything is outdated or wrong.

For 1, make sure the scripts are attached to two different objects and then in one object you reference the other object to see that value. Make sure the field is publicly assessable via get, not set.
Code examples: https://stackoverflow.com/questions/35657376/c-sharp-unity-trying-to-access-a-variable-from-another-script

For 2, transform.up is a vector2 (x,y grid) or vector3 (x,y,z grid) object that defines the up direction. For vector2 <x,y>; up is <0,1>, down is <0,-1>, left is <-1,0>, right is <1,0>.
Direction.up * speed * time is you distance the object should move from its current location on the grid.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #2 on: March 23, 2022, 02:11:53 AM »
Been a few years since I’ve messed with unity so apologies if anything is outdated or wrong.

For 1, make sure the scripts are attached to two different objects and then in one object you reference the other object to see that value. Make sure the field is publicly assessable via get, not set.
Code examples: https://stackoverflow.com/questions/35657376/c-sharp-unity-trying-to-access-a-variable-from-another-script

For 2, transform.up is a vector2 (x,y grid) or vector3 (x,y,z grid) object that defines the up direction. For vector2 <x,y>; up is <0,1>, down is <0,-1>, left is <-1,0>, right is <1,0>.
Direction.up * speed * time is you distance the object should move from its current location on the grid.

Thanks, both are really helpful.

So if you used transform.down the projectile would go backwards in reverse? aka up moves it forward in a positive distance.

Yeah for the first one it seems like it has to do with this GameObject.find thing. Will mess around but at least that gives me a starting point.

remy

  • my hog is small but it is mighty
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #3 on: March 23, 2022, 06:22:37 AM »
Uhh I don't think there is a transform.down. You just transform.up with a negative value

Quote
Like I don't understand how to pull an integer variable from one script (i.e. "currentPlayerHealth") and use it in another script in the same game/scene? Like as a test I wanted to write a script that just pulled that value and displayed it in the console log. But when I try to do that it has no idea what currentPlayerHealth is since it's a variable in another script. I feel like this is the most simple 101 stuff since you write modular and keep various pieces in their own scripts.

Put the currentPlayerHealth variable script on an object in the scene (maybe something like gameManager?) by making an empty or whatever and clicking add component. You can also drag scripts onto objects.

Put the second script on another object

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

public class gameManager : MonoBehaviour
{
   
    public int playerHealth;
    // Start is called before the first frame update
    void Start()
    {
        playerHealth = 20;
    }

    // Update is called once per frame
    void Update()
    {
         if (Input.GetKeyDown("s"))
        {
            playerHealth--;
        }
        if (Input.GetKeyDown("w"))
        {
            playerHealth++;
        }
    }
}



Then in the other script have something like this

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

public class healthCheck : MonoBehaviour
{
    public GameObject manageObj;
    public gameManager manager;
      public int health;
    // Start is called before the first frame update
    void Start()
    {
        manager= manageObj.GetComponent<gameManager>();
     
    }

    // Update is called once per frame
    void Update()
    {
    health= manager.playerHealth;
    }
}
Drag the gameObject that has the manager script on it onto the one the has the second script in the field that will have appeared. Apparently this is the best way to do this in unity.




You can do it in script but everyone says to just do it like this. The reason I've put get component in the start method and made a random object to use in update is because... calling getcomponent all the time is bad... apparently.

After that if you press w and s the number will change on both in the inspector. You could even add an input.GetKeyDown to the update method on script 2 to Debug.Log the variable if you want.

sorry if my explanation is moronic, i did this stuff as a hobby
« Last Edit: March 23, 2022, 06:34:42 AM by remy »

Nintex

  • Finish the Fight
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #4 on: March 23, 2022, 06:49:06 AM »
It's been a while since I coded anything in Unity but Remy is right.

It's a bit like LEGO. You first create all the seperate elements you need to build your game (objects and scripts to handle player health, damage, spawning, cloning etc.) and then you use those elements to create the actual game.
🤴

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #5 on: March 23, 2022, 11:36:39 AM »
Thanks Remy, yeah I guess the initial learning curve that I'll need to get past in Unity coding is getting used to mixing pure code with visual unity pieces dragging & dropping together.

My only past experience with code was pure code with no visuals so this whole writing piecemeal scripts to attach to objects as components thing in currently hard to process. But I've only taken like two one hour classes on Unity coding basics so far.

For the first 3 weeks of this class we didn't do any coding and it was all just drag and dropping stuff in Unity with pre-made scripts and textures/audio/prefabs. That was all straight forward. We're just now getting into modifying and writing scripts and that's a big jump there. I'm hoping to get a foothold quickly on basic script writing so I can use their pre-made materials to do some fun stuff.

Also we're supposed to start making our own sprites & animations & music. I know how to do basic music with apps, but gonna have to watch some youtube tutorials on how to make and animate a sprite this weekend because that's something I have zero experience with my entire life so far.

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #6 on: March 23, 2022, 11:59:14 AM »
for better understanding of transform.up:

you can think of it as a constant, it's literally just a stand-in for a number as skullfuckers said

you use transform.up instead of the literal number value because there could be a situation where your game might need to change what is considered to be "up," and in those cases you could change transform.up, rather than needing to track down all the places in the code where you typed a magic number that meant "up" at the time
Uncle

Propagandhim

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #7 on: March 23, 2022, 12:12:01 PM »
sounds like fun, bebpo.  post your project when your done!

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #8 on: March 23, 2022, 05:54:51 PM »
for better understanding of transform.up:

you can think of it as a constant, it's literally just a stand-in for a number as skullfuckers said

you use transform.up instead of the literal number value because there could be a situation where your game might need to change what is considered to be "up," and in those cases you could change transform.up, rather than needing to track down all the places in the code where you typed a magic number that meant "up" at the time

Thanks, so I'm guessing you define transform.up somewhere? That might be the issue, the code I'm working with from my class doesn't define it anywhere and uses it like a built in command in Unity.

I'm gonna assume the default for transform.up is like 1 unit?  So transform.up + speed (3) x distance (5) = go forward 18 units.

The reason I'm having a hard time understanding this initially is without defining transform.up, if transform.up = 1, then it seems extrafloues? Like if I would think you'd do transform.position (which say is (5,10) = transform.position + speed (3) x distance (5) and you'd still get 18, so from (5,10) you'd move to (23, 28)?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #9 on: March 23, 2022, 05:55:31 PM »
sounds like fun, bebpo.  post your project when your done!

hahahahaha, ok but it will be beyond bad.

I'll feel more comfortable positing my next class project after this one since at least I'll have a better understanding of what I'm doing next time.

Nintex

  • Finish the Fight
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #10 on: March 23, 2022, 07:11:40 PM »
Use floats for your calculations so they can be more precise.

This is something Satoru Iwata taught the INT heathens at Nintendo EAD  :heart
🤴

tiesto

  • ルカルカ★ナイトフィーバー
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #11 on: March 23, 2022, 07:45:56 PM »
Just curious, which class are you taking? I want to get into Unity dev (I do C# and .NET coding from time to time at work) but was looking for some good tutorials.
^_^

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #12 on: March 23, 2022, 11:50:40 PM »
Just curious, which class are you taking? I want to get into Unity dev (I do C# and .NET coding from time to time at work) but was looking for some good tutorials.

I searched around on Coursera reading reviews of various game development classes and went with this from Brian Winn at Michigan State University.

https://www.coursera.org/specializations/game-design-and-development

It's a 5 month course of 5 separate courses that build on each other.

Month 1 - Intro to game design, intro to Unity, build (or basically modify) an overhead 2d twin-stick shooter template into your own game.
Month 2 - Move into how to design 2d platformers in Unity. Should be more useful since it's an entire month course on just them. Make a 2d platformer by the end.
Month 3 - Move into FPS games in Unity. Make an FPS by the end.
Month 4 - Move into 3d platformers in Unity. Make a 3d platformer by the end.
Month 5 - Make your own original game

I'm at the end of Month 1. I've actually been running it at 2x speed because I enjoy this stuff so I got through all 4 weeks in about 2 weeks and just have the final project to do now which is due in about 10 days. I think it's pretty good so far. The reviews were quite good and most complaints were basically that it skips some of the lower level stuff that the lessons build on top of, so to understand the prefabs and stacks and stuff you need to spend some time on your own googling and youtubing certain things.

But I'd rather have that than a slow course where you spend hours doing basic stuff that puts you to sleep. I can't deal with that stuff and want to speedrun things at my age when learning new stuff. I'm willing to put the energy/time in in batches to get there.

From just looking around at how to do some of this stuff, there's tons of free youtube guides and other classes, but for me I like the idea of having deadlines and actually having to make 5 games in 5 months. Otherwise I probably would lose interest at some point after tinkering around. I'd never done Coursera before, it ain't exactly cheap at like $50/month (though you can take multiple classes at a time if you have the time), but a real class would be a couple hundred bucks for a semester so seems fair and putting money down is another thing that will motivate me to actually put the work in and get this done. I basically need the structure for my own way of learning, but that's different for everyone.

Also the main instructor for the class is pretty good! Good speaker and does a good job making sense of it and he's not too VIDEOGAMEZ cringy or anything. His TA who does some of the stuff though sounds dead inside and is much less entertaining.

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #13 on: March 24, 2022, 12:33:16 AM »
Quote
Do any of you code for your jobs?

Nah, I got out of that shitshow and now I only code for fun. ;)

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #14 on: March 24, 2022, 05:52:29 AM »
Quote
private void MoveProjectile()
    {
        transform.position = transform.position + transform.up * projectileSpeed * Time.deltaTime;
    }

I understand everything in that sentence except what "transform.up" is doing? It's saying the new position is the old position + speed x time. Which makes sense. I just don't get what transform.up is doing there.

Like Uncle says, that transform.up is a constant for Vector3(0,1,0) - Vectors are basically directions. I'm not sure if they're built in to Unity, or Monobehaviour (I'd guess Unity) but you see that Using... stuff at the top of your script? That's where transform.up is defined for you (probably). Also transform.down, transform.left, transform.forward, etc.

So breaking that script down 100% for you:
Code: [Select]
private void MoveProjectile()
 {
     transform.position += transform.up * projectileSpeed * Time.deltaTime;
 }

 - Thats a private method (can only be accessed from that script) that has no return value (its void) and has no input parameters (that empty brackets at the end)

 - It will move the gameobject it is attached to
      - In Unity's Y-axis
      - by variable projectileSpeed per frame
      - every averaged frame per second (Time.deltatime returns your FPS, and then averages it out so that the movement is smooth regardless of framerate or computer spec - if your PC was running this shit at 100fps, it might move 10 units per frame, if your PC was running it at 10fps it would move it 100 units per frame)

So I can tell that that method is being (or should be being) called from the Update() loop, because Update runs every frame - if you didn't actually want framerate indepedent movement (eg you're deliberately trying to recreate old school bullet hell shmup slowdown when shit gets frantic) you wouldn't be using Time.deltatime at all

I can also tell thats a pretty bad way of doing a projectile, because anything you're going to want to collide with things or be collided with that also moves in Unity is best done using a Rigidbody - manually changing somethings transform is a cheap way of moving something, but can and will fuck up physics interactions at a certain point / speed, and there's not really a good reason to not use even a simple physics movement (or a rb.position over a transform.position).

Like I don't understand how to pull an integer variable from one script (i.e. "currentPlayerHealth") and use it in another script in the same game/scene? Like as a test I wanted to write a script that just pulled that value and displayed it in the console log. But when I try to do that it has no idea what currentPlayerHealth is since it's a variable in another script. I feel like this is the most simple 101 stuff since you write modular and keep various pieces in their own scripts.

Gonna be watching lots of youtube tutorials this weekend and trying to write some scripts.

A lot of YT tuts fucking suck, because they literally go "Wassup guys, did you ever wanna make this mechanic? Cool, ok, do this, then do this, then do this, now hit play, cool huh? Don't forget to like and subscribe!" and don't explain shit, and even worse a lot of them have blatant fuck ups in their code they don't even acknowledge.
So if you got Q's, I can help with A's!

Getting scripts to talk to each other, there's a lot of different ways, but generally speaking, you're going to have some kind of trigger wanting to access a variable, and a LOT of those triggers are going to be collision based, so you just need to have a public method that things colliding with the gameobject can access; for example:

if you've got
Code: [Select]
public class BulletScript : monobehaviour
{
     [serializefield] float bulletSpeed, bulletDamage;

     void Update()
     {
          this.transform.position += vector3.forward * time.deltatime * bulletSpeed; // yeah I know what I said before about this being the bad way of doing this, but you know how to do this
     }

     public void DeleteBullet()
     {
          // you can call this from another script, eg when you spawn it with instantiate set it to self destruct after n seconds if it doesnt hit anything
     }

    void OnCollisionEnter(Collision col) // whatever you hit will be accessible from *this* script as col
    {
        if (col.gameObject.name == BadGuy)
        {
            col.EnemyScript.TakeDamage(bulletDamage);
            // you have a pointer to 'col' because the bullet just hit it, so you can access scripts on the things you just hit,
            // and trigger its EnemyScript via its public TakeDamage method, which takes a paramter youre sending from this bullet
            // - ie how much damage its doing
        }
    }
}

and

Code: [Select]
public class EnemyScript: monobehaviour
{
     [serializefield] float myHealth;

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.name == bulletPrefab)
        {
            col.BulletScript.DeleteBullet();
            // delete the bullet that just hit you
            // Note I wouldn't actually do this code this way, because order of execution might mean you delete the bullet before it does the damage,
            // but I'm just reinforcing how you can get a couple of scripts to talk to each other on a collision
        }
    }

     public void TakeDamage(float damage)
     {
          // this is called from the bullet hitting
          myHealth -= damage;
          if (myHealth<=0) { fuck im dead }
     }
}

as soon as the Bullet hits the Enemy, they can talk to each others scripts

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #15 on: March 24, 2022, 08:11:20 AM »
for better understanding of transform.up:

you can think of it as a constant, it's literally just a stand-in for a number as skullfuckers said

you use transform.up instead of the literal number value because there could be a situation where your game might need to change what is considered to be "up," and in those cases you could change transform.up, rather than needing to track down all the places in the code where you typed a magic number that meant "up" at the time

Thanks, so I'm guessing you define transform.up somewhere? That might be the issue, the code I'm working with from my class doesn't define it anywhere and uses it like a built in command in Unity.

I'm gonna assume the default for transform.up is like 1 unit?  So transform.up + speed (3) x distance (5) = go forward 18 units.

The reason I'm having a hard time understanding this initially is without defining transform.up, if transform.up = 1, then it seems extrafloues? Like if I would think you'd do transform.position (which say is (5,10) = transform.position + speed (3) x distance (5) and you'd still get 18, so from (5,10) you'd move to (23, 28)?

well I am far from an expert and very rusty

but in this specific case, you are working with a vector3 data type, which is a set of 3 values typically used as coordinates in 3D space in the form (x,y,z)

you're proposing just adding to it, but what happens if you add one number to a set of 3 numbers?

I honestly forget, either the program will throw you an error for mixing data types, or it will add that number to all three components of the vector3

so if you're at (5,10,0) and you add speed (3) * distance (5), that seems like it would result in adding 15 to each element, resulting in (20,25,15), so the object has moved in 3 ways at once in 3D space



instead, what the code is doing is multiplying transform.up by speed (and factoring in time)

so if speed is 3, and you multiply (0,1,0) by 3, you get (0,3,0), and when you add that to your position (5,10,0) you get (5,13,0), a movement only in the y direction (up)

(the multiply by deltaTime is going to shrink the value a lot to some small decimal value, because it's how much it moved in that one frame, 60 frames per second or whatever)



transform.[direction] vectors are intended to be multiplied, and the fact that they have zeroes in them is a way to say, "look I don't care what else is going on in this line of code, but we are only talking about this specific direction here, we're zeroing out everything else"
« Last Edit: March 24, 2022, 08:20:20 AM by Uncle »
Uncle

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #16 on: March 24, 2022, 08:34:46 AM »
I see you were the most recent person to mention Bad Rats on the bore a few months ago  :lol

it's a good example along these lines, one of its many issues is that it's a 2D game that doesn't always apply proper limitations to the Z direction, so objects can fall forward or backward out of the level and completely ruin the whole puzzle

there are many good, easy ways to solve this problem in Unity using its built-in physics controls/constraints, but just as an example here, you could say they DIDN'T multiply their objects' movement by transform.up or transform.right -- they didn't make sure that absolutely 0 movement can happen along the Z axis, and look what happens

Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #17 on: March 24, 2022, 01:21:05 PM »
Haha, ok that does make sense! I was wondering how Unity would apply a single digit transform to a vector3 and yeah if it applies to the Z axis you're gonna be bad rats fucked. So that makes sense.

Though for this 2d shooter project, being 2d and all I should just be using vector2s the whole time I think?

[lots of good stuff]

Thanks, this is extremely informative. A lot of what you wrote in the code sections is flying over my head but will spend time and try to parse and understand it all later when I have some time.

One comment though, you said the way the projectile code is written is bad and you should be using 2drigidbody. The thing is that my class project using the assets they give us (including that projectile code, which they say is the most simple script included), is using 2drigidbody. Like we had a whole session on rigidbody because when we first made the ship player and put an enemy with projectiles in the projectiles would just pass through the player ship until we added 2drigidboy and definied the hitbox.

Not sure what that means because this is beyond my scope of understanding that the projectile code is setup that way along with using rigidbody for collision.

Also I want to understand what you're saying about time.delta and shmup slowdown because if I can add shmup slowdown to this with a ton of bullets/enemies that would be kind of cool.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #18 on: March 24, 2022, 02:19:44 PM »
Though for this 2d shooter project, being 2d and all I should just be using vector2s the whole time I think?

You theoretically could, except there's a bunch of stuff that assumes a vector3 and will error if you give it a vector2 - off the top of my head, transform.position is one of them, and if you send it a vector2 it'll complain.

It'd be easy enough to make a method that takes a Vector2 input and spits out a Vector3 output to fix any of those examples though.


Thanks, this is extremely informative. A lot of what you wrote in the code sections is flying over my head but will spend time and try to parse and understand it all later when I have some time.

the only things you might not be immediately familiar with are
[serializefield] in my variables, and Oncollisionenter() having a Collider callback

[serializefield] is an attribute, that basically means the variable shows up in the unity inspector so you can mess with it outside of code, but you don't have to expose the variable as public (ie you don't need to let other scripts mess with it directly).

OnCollisionEnter is a prebuilt method (like Update() ), but it returns a pointer to the thing it collided with as a variable of type Collider, so you can access it.

One comment though, you said the way the projectile code is written is bad and you should be using 2drigidbody. The thing is that my class project using the assets they give us (including that projectile code, which they say is the most simple script included), is using 2drigidbody. Like we had a whole session on rigidbody because when we first made the ship player and put an enemy with projectiles in the projectiles would just pass through the player ship until we added 2drigidboy and definied the hitbox.

Not sure what that means because this is beyond my scope of understanding that the projectile code is setup that way along with using rigidbody for collision.

Basically, Unity is running 2 simultaneous timers; one is the rendering timer, which by default runs at 60 ticks per second and is called from Update()
The other is the Physics timer, which by default runs at... 25? ticks per second, and is called from FixedUpdate()

A rigidbody component basically just tells Unity the thing its attached to has 'physics' and it should keep an eye on it for things like collisions.

Generally you want to put anything physics related into FixedUpdate rather than Update, so Unity knows about it and is checking on the physics tick, not the rendering tick.

So if you just wanted to have like... clouds and shit flying past in the background, you could use a basic transform.position on them in the Update() loop.

Something like a bullet though, you probably want to move the rigidbody (which the simplest movement is just rigidbody.position) rather than the thing the rigidbodys attached to, and do that in FixedUpdate().
Its basically more reliable in terms of 'catching' collisions, as you can probably imagine moving stuff thats supposed to interact with each other at entirely different tick rates is kinda sketchy.

Also I want to understand what you're saying about time.delta and shmup slowdown because if I can add shmup slowdown to this with a ton of bullets/enemies that would be kind of cool.

Time.deltatime is there to give the impression of smooth framerate, even when its not, and anything in Update() is directly tied to framerate - oldschool games didn't have two different timers, they had one thread, so when that shit got busy, the whole game slowed down because the framerate was the speed the game was actually running at.
With Unity (and most modern engines I think) having rendering done separately to game logic means you get gameplay independent of framerate, so your dude moving at 10m/s at 100fps is the same 10m/s as someone else playing at 10fps, they just move each of you a different amount per frame so it averages out over a second.

For deliberate bullet time type shit, you can mess with time.timescale which will slow / speed up time itself; this will fuck with time.deltatime, but if you still need that for smoothing during bullet time or whatever, you can make your own version based on uhhhhhh time.realtimesincestartup or something, then average that out to get your own averaged time per second value.
(I only know this because the UI animations used to be linked to Time.deltatime, and if you did ez mode pause button of timescale=0 the fucking ui stopped working :rofl )

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #19 on: March 24, 2022, 03:10:50 PM »
Haha, ok that does make sense! I was wondering how Unity would apply a single digit transform to a vector3 and yeah if it applies to the Z axis you're gonna be bad rats fucked. So that makes sense.

Though for this 2d shooter project, being 2d and all I should just be using vector2s the whole time I think?

I am pretty sure the way it works is that Unity is always inherently 3D under the hood, even in a 2D project, so technically all positions are vector3s, but if you use vector2s it just treats the Z axis as 0

I think they even implicitly convert between the two, so you can set a vector2 equal to a vector3 and it will just grab the X and Y
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #20 on: March 24, 2022, 08:11:03 PM »
Brainstorming a bit on my walk today for some ideas that may be relatively intro level/simple to program for a 2d shooter,

One idea is like you can absorb bullets (aka visible bullet counter goes up on collision) which makes your bullets stronger (bulletStrength = BulletStrength x BulletCounter) but you die after like 5 bullets (if oncollision bullet counter = 5; you ded), so you can either glass cannon it with 3-4 bullets absorbed doing 3-4x damage, or you can take it slow and have some extra hits.

This seems like it should be easy to program in, but idk if it would be much fun for gameplay considering the stages/enemies at a basic intro level game are not going to have the depth to make that balancing act meaningful. You'd need to have a lot of bullets and maybe some sub-system to add depth.

Like if you could purge your bulletcounter and gain invuln for 1/4th second for each bullet purge. So if maximum bullets you can hold is 4 before dying at 5, purging all 4 gives 1 full second of invuln.

Not sure if that would be too much complexity in programming for me, but maybe those sub-systems would be enough for 3 short stages vertical slice game jam kinda thing.


The other idea I had was doing an absurd comedy using public domain images of old famous people from like 1800s or earlier. Basically "this is the future where famous artists have been cloned and now there is an alien attack at an artist convention in 21xx" and you play a shmup where at various points in the stage a random number generator throws out a random little ship with a HUD pop up of some photo/painting of like BEETHOVEN and he's like "RED-5 I'M GO FOR LAUNCH" and a little audio clip of Beethoven plays and you can catch him and he joins your ship squadron (no real AI, just attachs to your ship at an offset position and maybe shoots forward) or you can shoot him and he blows up with a scream and you get his unique power up.

At the end of the game the victory screen lists off artists killed this run, along with a scream for each name that appears, and then you get an ending which is based on which squadron mates survived. Like there'd be a dozen famous people and they'd each have their own ending clip SF2 win screen style with them talking to you for a line. They'd all have unique power-ups.

So you can murder them all and have a bunch of cool power-ups and the ending is you all alone in darkness, or you can save them all and have the best ending where a bunch of classical artists are having a party with you.

From a programming perspective, once I could get one AI pod working, there wouldn't be much programming to just keep adding more and more (mostly just figuring out scripting power-ups) and would be more on the art side of adding art/audioclip/ending screen.

Oh and the name of the game would be "Every Ship is Sacred" punning the every sperm is sacred Monty Python song. I was thinking of an every bullet is sacred game where every bullet that is shot by you has a name and when it collides with something the game says like JERRY HAS DIED and there's a wilhelm scream on collision but I feel like to make that work you'd need a fire rate of like 1 bullet per 20 seconds or something and idk how I'd make that even work and fun in a gameplay loop. If you could have a random name generator I guess you could get by with like every second it scrolling through all the names of people dying as you are shooting them out and the ending screen could be a credit scroll listing the name of every person you killed by firing them as bullets. Would be kind of dark haha and need a story reason for why you are firing people out of your ship.

archnemesis

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #21 on: March 25, 2022, 02:08:23 AM »
This Udemy Course is quite good for 2D shooters. It introduces some more advanced concepts, e.g. using coroutines for power-ups. It's definitely worth the €15.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #22 on: March 25, 2022, 06:18:34 PM »
Ok, done with work for the week. Got no plans this weekend so gonna start working on code for the next 2.5 days and try to understand everything in GreatSage's posts.

therealdeal

  • Member
Re: Do any of you code for your jobs?
« Reply #23 on: March 25, 2022, 06:20:35 PM »
Unity is dope af. I've made just like, a 3d maze runner, and 3d parkour level with obstacles. But I'd like to spend more time with it again, finish the course I was doing

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #24 on: March 27, 2022, 04:18:09 AM »
Been working on this and first thing was trying to figure out how to get an enemy to move left & right. Watched a youtube vid and it made sense (it put left & right waypoints as GameObjects so you could put them on the screen borders or platform borders and then it basically said move right until right border then move left until left border)

spoiler (click to show/hide)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test_Move : MonoBehaviour
{
    public float EnemyMoveSpeed = 1.0f;
    Transform leftWayPoint, rightWayPoint;
    Vector3 localScale;
    public bool movingRight = true;
    Rigidbody2D rb;


    void Start()
    {
        localScale = transform.localScale;
        rb = GetComponent<Rigidbody2D>();
        leftWayPoint = GameObject.Find("LeftWayPoint").GetComponent<Transform>();
        rightWayPoint = GameObject.Find("RightWayPoint").GetComponent<Transform>();
    }


    // Update is called once per frame
    void Update()
    {
   
        if (transform.position.x > rightWayPoint.position.x)
            movingRight = false;
        if (transform.position.x < leftWayPoint.position.x)
            movingRight = true;

        if (movingRight)
            moveRight();
        else
            moveLeft();

    }

    void moveRight()
    {
        movingRight = true;
        localScale.x = 1;
        transform.localScale = localScale;
        rb.velocity = new Vector2(transform.localScale.x * EnemyMoveSpeed, rb.velocity.y);

    }

    void moveLeft()
    {
        movingRight = false;
        localScale.x = -1;
        transform.localScale = localScale;
        rb.velocity = new Vector2(transform.localScale.x * EnemyMoveSpeed, rb.velocity.y);
    }
}
[close]

I understand pretty much everything in that code, outside rb.velocity which I guess is a built in Unity thing about movement that I should look up the Unity help to see what it does.

This code worked and my little enemy sprite moves back and forth like space invaders now.

So then I looked up the script my class has for enemy which includes movement modes. One thing is the class I'm taking doesn't use localScale but like every tutorial I see online uses localScale. I like how in the code above you just set the localScale for x as either positive (1) or negative (-1) to determine the direction on the X movement.

Without localScale...I don't know how to simply set right x = 1, or x = -1 for movement direction.

The way my class script does it is...complicated. The enemy script is really long and maybe I'll put more of it up later since I tried going through it and understanding each line (that's one way I'm trying to learn, is read all the scripts provided and try to understand each line). For movement on a scrolling movement the code is:

spoiler (click to show/hide)
private void MoveEnemy()
    {
        // Determine correct movement
        Vector3 movement = GetDesiredMovement();

        // Determine correct rotation
        Quaternion rotationToTarget = GetDesiredRotation();

        // Move and rotate the enemy
        transform.position = transform.position + movement;
        transform.rotation = rotationToTarget;
    }

    protected virtual Vector3 GetDesiredMovement()
    {
        Vector3 movement;
        switch(movementMode)
        {
            case MovementModes.FollowTarget:
                movement = GetFollowPlayerMovement();
                break;
            case MovementModes.Scroll:
                movement = GetScrollingMovement();
                break;
            default:
                movement = Vector3.zero;
                break;
        }
        return movement;
    }

    protected virtual Quaternion GetDesiredRotation()
    {
        Quaternion rotation;
        switch (movementMode)
        {
            case MovementModes.FollowTarget:
                rotation = GetFollowPlayerRotation();
                break;
            case MovementModes.Scroll:
                rotation = GetScrollingRotation();
                break;
            default:
                rotation = transform.rotation; ;
                break;
        }
        return rotation;
    }

   private Vector3 GetScrollingMovement()
    {
        scrollDirection = GetScrollDirection();
        Vector3 movement = scrollDirection * moveSpeed * Time.deltaTime;
        return movement;
    }
 
    private Quaternion GetScrollingRotation()
    {
        return Quaternion.identity;
    }

    private Vector3 GetScrollDirection()
    {
        Camera camera = Camera.main;
        if (camera != null)
        {
            Vector2 screenPosition = camera.WorldToScreenPoint(transform.position);
            Rect screenRect = camera.pixelRect;
            if (!screenRect.Contains(screenPosition))
            {
                return scrollDirection * -1;
            }
        }
        return scrollDirection;
    }
[close]

Now I can follow that until this part which is all gibberish to me and seems highly complex for just figuring the direction to go left or right?
Quote
    private Vector3 GetScrollDirection()
    {
        Camera camera = Camera.main;
        if (camera != null)
        {
            Vector2 screenPosition = camera.WorldToScreenPoint(transform.position);
            Rect screenRect = camera.pixelRect;
            if (!screenRect.Contains(screenPosition))
            {
                return scrollDirection * -1;
            }
        }
        return scrollDirection;

"Rect screenRect = camera.pixelRect"

Creates a rectangle called screenRect, ok I get that. But I don't know what camera.pixelRect means. Also that if statement kinda breaks my brain.
« Last Edit: March 27, 2022, 04:22:15 AM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #25 on: March 27, 2022, 04:20:48 AM »
Also just figuring out movements and stuff already feels like hard maths and I am so bad at maths :(

I actually started college as a comp sci major taking C++ classes and what got me to quit the major was I got As in programming but Ds in higher level math and you needed both for the major. I'm ok with math when it has numbers, but when it's variables it breaks my brain  :'(

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #26 on: March 27, 2022, 04:23:55 AM »
One thing I don't like btw in the script stuff the class provides is the enemy projectile that is fired bounces off the walls (but doesn't have hit collision on the player on the ricocheted bullets. I have no idea what is wrong with their physics (using rigidbody2d) that would make the projectile shots bounce off the walls instead of being destroyed upon hitting a wall.

Definitely something I want to try to fix as I'm modifying this project. It's a little thing but it looks sloppy.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #27 on: March 27, 2022, 07:35:22 AM »
I understand pretty much everything in that code, outside rb.velocity which I guess is a built in Unity thing about movement that I should look up the Unity help to see what it does.

Its using the inbuilt physics system (the rb is a cached RigidBody, so its applying it to that Rigidbody) to set the velocity immediately to the var you provided - ie, its ignoring any initial friction or acceleration or deceleration values to just make the thing ROOOOOOOOOOOLLLLLLLLLLLLLLLLLLLLLLING STAAAAAAAAAAAAAAAAART

This code worked and my little enemy sprite moves back and forth like space invaders now.

Another way you could do this without the 'edge of screen' gameobjects is to specify your Bounds manually;
eg if you know 'top of screen' is 8Y, bottom is -8Y, left is -12X and right is 12X (or whatever) you could do something like (pseudocode)
Code: [Select]
bool goingLeft=true;
if (pos.X>=12) { goingLeft=false; }
else if (pos.X<=-12) { goingLeft=true; }

if (goingLeft) { transform.pos += speed; }
else { transform.pos -= speed; }

// same again for Y boundaries if you need them

// you can also do somthing like
movementX = mathfclamp(-12,12)(input.getaxis("horizontal"));
movementY = mathfclamp(-8,8)(input.getaxis("vertical"));
// to lock player movement to bounds
You can also automagically generate those bounds by getting camera information (ie what the camera can see = playspace boundaries)
solid edge colliders are a good idea for other reasons though, like you can use them to get rid of stuff thats out of bounds so you dont have ghost bullets a thousand miles offscreen etc

So then I looked up the script my class has for enemy which includes movement modes. One thing is the class I'm taking doesn't use localScale but like every tutorial I see online uses localScale. I like how in the code above you just set the localScale for x as either positive (1) or negative (-1) to determine the direction on the X movement.

adjusting transform.localscale -1 is usually used because it 'flips' the gameobject, so if it has a different left / right sprite, or an irregular collider, it will be completely mirrored by doing that - I suspect that's why they're doing it that way more than just the movement aspect

Without localScale...I don't know how to simply set right x = 1, or x = -1 for movement direction.

Like my pseudocode above, you can just set a boolean for 'am I going in the right direction?' and flip it when you want them to.
Also don't forget you've got Vector.Right and Vector.Left if you want to be super explicit, eg
Code: [Select]
if (movingRight) { transform.pos += Vector2.Right * Movespeed * Time.deltatime; }
else { transform.pos += Vector2.Left * Movespeed * Time.deltatime; }
The way my class script does it is...complicated. The enemy script is really long and maybe I'll put more of it up later since I tried going through it and understanding each line (that's one way I'm trying to learn, is read all the scripts provided and try to understand each line). For movement on a scrolling movement the code is:
...
Now I can follow that until this part which is all gibberish to me and seems highly complex for just figuring the direction to go left or right?
Quote
    private Vector3 GetScrollDirection()
    {
        Camera camera = Camera.main;
        if (camera != null)
        {
            Vector2 screenPosition = camera.WorldToScreenPoint(transform.position);
            Rect screenRect = camera.pixelRect;
            if (!screenRect.Contains(screenPosition))
            {
                return scrollDirection * -1;
            }
        }
        return scrollDirection;

"Rect screenRect = camera.pixelRect"

Creates a rectangle called screenRect, ok I get that. But I don't know what camera.pixelRect means. Also that if statement kinda breaks my brain.

So I guess what that code is doing is moving the enemies AND also the background?  ???
The camera stuff is - like I hinted above, about setting the boundaries of the playspace to what the camera can see - finding the 'edges' of the camera viewpoint, and I would guess what its then doing thats not shown is jumping the background image from one 'side' of the camera to the other to give the illusion of a seamless scrolling BG?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #28 on: March 27, 2022, 01:54:14 PM »
Ooooh, thanks! I actually am starting to get this. I tested the boundaries you talked about and then modified the script so now you can just set boundaries for anything in Unity as a public entry.

And it works!

I think this is the first piece of code I've written myself that's worked lol. Next I'm going to try removing localScale and using vector.left, vector.right to simplify it more since pretty sure scale doesn't matter in this project.


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

public class Test_Move : MonoBehaviour
{
    public float EnemyMoveSpeed = 1.0f;
    Vector3 localScale;
    public bool movingRight = true;
    public float leftBoundary = -1.0f;
    public float rightBoundary = 1.0f;
    Rigidbody2D rb;


    void Start()
    {
        localScale = transform.localScale;
        rb = GetComponent<Rigidbody2D>();
    }


    // Update is called once per frame
    void Update()
    {
   
        if (transform.position.x > rightBoundary)
            movingRight = false;
        if (transform.position.x < leftBoundary)
            movingRight = true;

        if (movingRight)
            moveRight();
        else
            moveLeft();

    }

    void moveRight()
    {
        movingRight = true;
        localScale.x = 1;
        transform.localScale = localScale;
        rb.velocity = new Vector2(transform.localScale.x * EnemyMoveSpeed, rb.velocity.y);

    }

    void moveLeft()
    {
        movingRight = false;
        localScale.x = -1;
        transform.localScale = localScale;
        rb.velocity = new Vector2(transform.localScale.x * EnemyMoveSpeed, rb.velocity.y);
    }
}

Also I wonder what happens if I get rid of rigidbody & velocity. Will try & see...

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #29 on: March 27, 2022, 01:57:06 PM »
Also is there an easy way to backup versions of code before you fuck with them and potentially break them and forget how it was setup before you broke it?

Right now I'm doing Unity right click "show in folder" -> copy .cs file to desktop & rename as backup. Feel like there must be an easier way to do this.

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #30 on: March 27, 2022, 01:57:49 PM »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #31 on: March 27, 2022, 02:11:31 PM »
So I got rid of localscale & truncated the code and it still works.

I'm trying to get rid of rigidbody and make the code as short and simple as possible. I know this doesn't work, but logically can someone explain why this doesn't work?

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

public class Test_Move : MonoBehaviour
{
    public float EnemyMoveSpeed = 1.0f;
    public bool movingRight = true;
    public float leftBoundary = -1.0f;
    public float rightBoundary = 1.0f;


    void Update()
    {
   
        if (transform.position.x > rightBoundary)
            movingRight = false;
        if (transform.position.x < leftBoundary)
            movingRight = true;

        if (movingRight)
            transform.position.x + (1 * EnemyMoveSpeed);
        else
            transform.position.x + (-1 * EnemyMoveSpeed);

    }

}

Why can't you just tell it, if you're moving right, change the X position of the object to say X+1 each update and if you're moving left change the position of X to X-1 each update? Logically that should mean the enemy moves from 4 to 5 to 6, though I'm guessing even if this did work the enemy would teleport from 4 to 5 to 6 each frame without actually moving in the .0 space between since this doesn't give it any actual velocity.

So this code would suck, but I'm trying to figure out why logically it won't work. Visual studio tells me "only assignment, call increment, decrement, await and new object expressions can be used as a statement"

Well, I want to increment going right and decrement going left, so how do you do that?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #32 on: March 27, 2022, 02:13:41 PM »
btw, this is as truncated as I've gotten this without using localscale and still having it function as intended.

spoiler (click to show/hide)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test_Move : MonoBehaviour
{
    public float EnemyMoveSpeed = 1.0f;
    public bool movingRight = true;
    public float leftBoundary = -1.0f;
    public float rightBoundary = 1.0f;
    Rigidbody2D rb;


    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }


    // Update is called once per frame
    void Update()
    {
   
        if (transform.position.x > rightBoundary)
            movingRight = false;
        if (transform.position.x < leftBoundary)
            movingRight = true;

        if (movingRight)
            moveRight();
        else
            moveLeft();

    }

    void moveRight()
    {
        movingRight = true;
        rb.velocity = new Vector2(1 * EnemyMoveSpeed, rb.velocity.y);

    }

    void moveLeft()
    {
        movingRight = false;
        rb.velocity = new Vector2(-1 * EnemyMoveSpeed, rb.velocity.y);
    }
}
[close]

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #33 on: March 27, 2022, 02:18:04 PM »
Also next thing I'm trying to learn this morning is how to spawn bullet hell patterns instead of just like the enemy shooting 1 shot forward. I want an explosion of bullets coming from certain enemies Cave style.

Then will look into designing power-ups.

Then will try to implement my bullet retention & damage up & purge invincibility concept I thought of.

Then will try to learn to make a sprite enemy for my bullet hell dispersement and make a power-up sprite.


Pretty much goals for today. If I can learn this stuff I can start trying to make some stages tomorrow after work from it.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #34 on: March 27, 2022, 02:20:47 PM »
Also I wonder what happens if I get rid of rigidbody & velocity. Will try & see...

So you know that
Code: [Select]
transform.position += direction * speed * Time.deltatimemovement code you posted earlier, and had figured out how it works?

You can pretty much literally rewrite that to use a rigidbody rather than a transform and do the same type of movement, but onto your physics object rather than setting it a velocity (especially if you don't need to inherit velocity.y as you are doing, ie gravity).
Try putting:
Code: [Select]
rb.position += direction * speed * Time.fixeddeltatimeinto your fixed update loop - if you're not trying to use Full Fat Physics, often 'rolling your own' Reduced Fat Physics (ie just the collisions part, and writing your own specific movement code) can get nicer results - you'll notice this especially when you're doing shit like creating frictionless physics materials to avoid inertia, or making gravity ridiculously high, or fucking with your players mass to try and get the 'feel' you want; when you start doing stuff like that, thats the time to just set things up how you want them from scratch.

Also is there an easy way to backup versions of code before you fuck with them and potentially break them and forget how it was setup before you broke it?

Right now I'm doing Unity right click "show in folder" -> copy .cs file to desktop & rename as backup. Feel like there must be an easier way to do this.

Githubs free :idont
If you dont wanna / can't, you can just go to the Assets menu and Export a package then use that as version control


GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #35 on: March 27, 2022, 02:24:11 PM »
Visual studio tells me "only assignment, call increment, decrement, await and new object expressions can be used as a statement"

VS is being as helpful as VS knows how to be - look at the previous working one, where you're saying "Set this value to be a blank value, but with these bits changed" and what your not-working code is saying is "this value Adds bits changed"

e: what you want to be saying is "set this value to be the old value, plus the changed bit" - not gonna post the code, see if you can figure it out.
Also don't forget adding a negative to a positive can result in a negative, so you don't necessarily need 2 lines of code to handle the actual movement of going left / right.
« Last Edit: March 27, 2022, 02:31:04 PM by GreatSageEqualOfHeaven »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #36 on: March 27, 2022, 02:32:07 PM »
Oh I'm dumb, guessing I should be doing the +=, will try that out in a bit.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #37 on: March 27, 2022, 03:49:49 PM »
Hmmm, starting to come together mentally even without watching tutorials.

Like for bullets, rather than thinking of them as projectiles from enemies, I could make a spawner that spawns bullet objects in whatever directions at whatever speed I want and then just attach that spawner to an enemy.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #38 on: March 27, 2022, 05:35:58 PM »
See if you can figure it out.

Hey I did it!

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

public class Test_Move : MonoBehaviour
{
    public float EnemyMoveSpeed = 1.0f;
    public bool movingRight = true;
    public float leftBoundary = -1.0f;
    public float rightBoundary = 1.0f;


    void Update()
    {
   
        if (transform.position.x > rightBoundary)
            movingRight = false;
        if (transform.position.x < leftBoundary)
            movingRight = true;

        if (movingRight)
            transform.position = new Vector2(transform.position.x + (1* EnemyMoveSpeed * Time.deltaTime), transform.position.y);
        else
            transform.position = new Vector2(transform.position.x + (-1* EnemyMoveSpeed * Time.deltaTime), transform.position.y);

    }

}

Doesn't even skip around like I expected it to but smoothly moves just like when using rb velocity? Not sure conceptually why it's not teleporting units but I guess it's calling update like 60 times a second and incrementally teleporting it 60 movements in a second so to the eye it looks like it's moving smoothly.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #39 on: March 27, 2022, 05:40:29 PM »
So I watched this video and for the most part understood it and made a bullet which moves at a speed & in a direction, a bulletpool that keeps refilling bullets as they are destroyed, and a firebullet that fires the bullets at a set angle spread (the angle stuff is just a bit beyond my math understanding so I'm just stealing that bit without fulling understanding how to set a spread rotation).



I then added 2d rigid body to the bullet prefab and added my class's damage script to it so it can do damage to the player ship on collision.


It all works good except I'm running into 1 problem that I need help figuring out. Basically the bullet script for the bullet prefab gives them a life of 3 secs and then the gameobject is destroyed. Bulletpool then refills on new bullets.

But if a bullet hits my ship or hits a border and the bullet gameobject is then destroyed, it's being destroyed early and the bulletpool gets an error because one of the gameobjects it was using "bullet" is missing and the game crashes.

How do I get around this? I guess the abstract question of this, is if you destroy a gameobject that has stuff connected to it, how do you avoid a runtime error. Can you just go through all the attached codes and add "if alive" before it or is there an easier way to deal with the issue.

*edit* I think I'll try to figure this out myself looking at the bullet destroy object method and the destroy on damage object method and see how they do things differently.
« Last Edit: March 27, 2022, 07:13:59 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #40 on: March 27, 2022, 08:05:54 PM »
Ok, I figured out the issue. The way I'm spawning bullets and firing them using the above video method, the bullet objects aren't being destroyed. They being setactive(false) when they're done and then returned back to the queue to be set active and fired again. So if you're firing 20 bullets at a time, it's the same 20 bullets firing or something over and over.

The damage script actually destroys the bullet gameobject that's created and is in the hierarchy.

Thus when it's destroyed, it's no long in existence and the bulletpool is looking for a bullet #3 on the list which it expects to be false to requeue, but the bullet has vanished because it's been destroyed.

I can fix this by changing the damage method to setActive(false) instead of destroy. And the game works fine and bullets destroy on impact and don't crash the game. But I also get a few warnings that there's some script fuck ups going on because the destroy reference in damage has now vanished.

Not sure how I can leave destroy in and adjust the bulletpool since it would just the entire bulletpooling method if the bullets are destroyed. Seems better to try to change anything referencing the damage script and destroys line.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #41 on: March 27, 2022, 09:26:43 PM »
Let's see.

I got the asteroids wall boundaries to kill my character, which is good.


But otherwise spent the last two hours trying to get chasing bullets working. Don't even care about the spread, I just want stationary bullets fired from turrets to point in the player ships direction when initializing and shoot in a straight line in that direction.

There's a sample code here:
https://answers.unity.com/questions/1785183/how-to-make-3-bullets-fire-at-different-angles.html

And it works on its own scene but it doesn't work with my scene. The main issue I think is that this code uses a script called "Player" for the Player, whereas the Player ship in my game doesn't have a Player script, it just has a controller script.

I cannot for the life of me figure out how to get this script to work in my game:

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

public class Enemy : MonoBehaviour
{
    Player _target;
   
    public Bullet BulletPrefab;
    public float SideBulletAngle = 30f;
    public float FireInterval = .2f;

    void Awake()
    {
        _target = FindObjectOfType<Player>();     
    }

    private void OnEnable()
    {
        StartCoroutine(Fire());
    }

    private IEnumerator Fire()
    {
        while(enabled)
        {
            Fire(-SideBulletAngle);
            Fire(0);
            Fire(SideBulletAngle);

            yield return new WaitForSeconds(FireInterval);
        }
    }

    void Fire(float angle)
    {
        var bullet = Instantiate(BulletPrefab, transform.position, Quaternion.identity);
        bullet.Initialize(_target.transform.position, angle);
    }
}

I just want to get that bullet.Initialize (at my player.transform.position, angle) for my own bullet types. But I can't figure it out and getting a bit frustrated at the wasted time and no progress (which I guess is pretty normal when coding).

Should move on to something else at this point. I'm trying to learn the whole kitchen sink of shmups for my first project in like 1.5 weeks I have when all the project is asking me to do is take their basic game template and make 3 minor mods to it (either with new script actions, new sprites or new music). Maybe I should save making an entirely different game for the next game when I have 4 weeks to do it.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #42 on: March 27, 2022, 09:34:11 PM »
At this point, in terms of like a game plan, if I wanted to learn everything that I want to have the basic tools to make a shmup I'd need to learn:

1. How to make a vertically scrolling 2d main camera that either kills your player ship or drags them along the bottom if they try to go out of bounds.

2. How to make that camera stop at a boss.

3. How to make stage victory condition being to kill a boss which goes to stage score screen (this seems like it should be pretty easy)

4. How to give a boss multiple phases, so on awake, start with patterns 1 & 2, at 50% move to patterns 3 & 4

5. How to make power-ups (spread shot, extra stationary support ships that fire forward, shield, etc...)

6. How to make pick up objects for power-ups (probably just gameobjects that destroy on collision but instead of causing damage give power-up)

7. How to implement the gameplay system I want.

8. How to make enemies spawn in a vertical stage (this should be pretty straight-forward with a spawner that creates them in time intervals and moving in a direction)

9. How to make sprites for enemies/power-ups/ship

10. How to animate sprites.

11. How to make stage music.

12. How to make multiple different types of bullet patterns (what I'm working on now, basically have straight down shot and bullet hell circle shots, just need chaser shots really)


I think that's the bulk of the tools I'd want to get under my belt to then sit down and design out a couple of levels and boss patterns. But that's a lot of stuff and my project's due at the end of the week and at most I have a few hours each weeknight. Soooo, yeah maybe gonna keep it simple and try something more like this on the next project.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #43 on: March 27, 2022, 11:48:34 PM »
Well I made a vertically scrolling BG loop. Didn't figure out player boundaries so I can just fly out of the game area or any way to drag a player who is falling out of the scrolling BG. Mainly because the player movement script controller is weird and I can't just set min/max movement positions at the start based on the game canvas.

Spent the last 90 mins trying to fix this dumb respawn in the base code provided. The ship instantly respawns while the old death animation is still playing and it looks bad. Plus the ship jumps to the initial starting spot on each respawn which is jarring. Tried to fit in WaitforSeconds delay timer but couldn't make it work.

I definitely feel like trying to use this code base provided which does things its own non-orthodox way with original code and stuff I'm learning online is just a frankenstein nightmare of a mess and it's pretty disheartening spending all this time and very little ever works. I think I'd make more progress just starting from scratch outside art assets and making my own code instead of trying to use the classes' weirdly complex with lots of quirks code.

Maybe next project I'll just do everything from scratch instead of using their code.

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #44 on: March 28, 2022, 01:52:04 AM »
I remember the excitement coding my first games. :uguu

First trying DarkBasic, then C++, then C#, then XNA, then finally JavaScript.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #45 on: March 28, 2022, 02:00:03 AM »
Yeah, I talked with a coder friend and this is just a bad idea the way I'm approaching learning C# & Unity. Basically trying to reverse engineer code I don't understand and google and ask people and reading the Unity help website.

I've only been coding Unity/C# for like...less than one week and I'm trying to do essentially intermediate tactics and even the Udemy 2d shmup guide says it's for intermediate C# programmers and after one week I am definitely not there.


Instead of trying to make the best full fledged shmup ever in my first week of code. I really need to learn the basics and practice and do them over and over until I'm comfortable with the simple stuff before delving into the intermediate things you'd actually want to use to make a game. Learn what the hell enum means, get comfortable with serializedlists and all kinds of transform positioning and rotations, learn what yield does, etc...etc....

Now maybe the next part of this class I'm taking will start to do that. It's a 5 month class and this just the end of month 1. I'll give it a shot and if it's not explaining the basic stuff then I'll look into picking up a book on beginner level C# and/or take a class on it.

Probably need to spend at least 2-3 months on beginner C# and put my time in. Otherwise just gonna keep getting frustrated trying to jump straight into intermediate coding where I only vaguely understand what's going on and am constantly stumped and frustrated.


Gonna take a break from the coding-side and focus next session on learning some basic beginner pixel sprite stuff. Should at least be able to swap/edit/create a few simple sprites and a music loop before turning in this project.

Nintex

  • Finish the Fight
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #46 on: March 28, 2022, 03:54:43 AM »
Kill half your features.
Fake the rest

Welcome to game development  8)
🤴

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #47 on: March 28, 2022, 01:36:21 PM »
Instead of trying to make the best full fledged shmup ever in my first week of code. I really need to learn the basics and practice and do them over and over until I'm comfortable with the simple stuff before delving into the intermediate things you'd actually want to use to make a game.

Yeah, this is probably a good idea; what I'd suggest you do is:
 - Using your Frankenstein script for reference if you need it (but try using docs.unity.com as a first point of reference) try and recreate a SHMUP at its most basics, with the stuff you're secure you know
 - so rb.position += inputs * movespeed * time.fixedelattime movement for your player
 - rb.position += vector2.right * movespeed for a bullet script thats always moving
 - instantiate(bulletprefab,firepoint.position,bullet.rotation) to shoot bullets
 - clamping movement to the screen bounds
 - bullets self destruct if they go outside the bounds (ignore object pooling for now)
 - bullets do damage to a thing they hit when they hit it, then self destruct

when you've got those down, and can pretty much recreate from memory, then start freestyling new mechanics onto your solid code base.


Having said that, if you want me to explain anything in particular better, let me know - I'm not doing a multiline quote of your like, 10 posts in a row though  :lol

demi

  • cooler than willco
  • Administrator
Re: Do any of you code for your jobs?
« Reply #48 on: March 28, 2022, 03:01:27 PM »
Dedicate your energy towards rom translations instead
fat

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #49 on: March 28, 2022, 03:44:26 PM »
Having said that, if you want me to explain anything in particular better, let me know - I'm not doing a multiline quote of your like, 10 posts in a row though  :lol

I think I just want to get clamping working for movement.

The player movement code in my template is very complicated and there is no clamping because it was meant for a top-down free roam kind of map where the camera follows the player and you build actual walls on the outside.

This does not work for my vertically scrolling shmup stage I made.


My guess is there are 3 approaches to get clamping working on this stage:

1. I try to understand the player controls code provided and try to figure out how to work clamping into their complex code.
 -Most likely this will fail and be hours of frustration because I don't understand a lot of the code provided and there is no explanation in the class for it since we weren't supposed to be messing with it yet.

2. I uncheck the player controller script and just write a simple 6 line one with clamping.
-This seems easy and should work, but the problem is if some of the other template game scripts are referencing stuff in the player controller script I just disabled. I can at least try this and see.

3. I don't do clamping and for my vertical stage I create an actually thin border object that frames the main camera and has collision physics checked (but no damage) and therefore create a wall that keeps boundaries even with the scrolling stage. Instead of being giant wall of asteroids like the template stage it'll just be a thin line that looks like a natural HUD frame border.
-This should work if #2 fails and shouldn't be too much work.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #50 on: March 28, 2022, 03:45:32 PM »
Dedicate your energy towards rom translations instead

Hasn't everything decent been translated already?

I used to do translations for things I was passionate about that weren't available in English. I can't think of any game that's JPN only still that I'd care about enough to want to spend the time. We are in a pretty good time for jrpgs in English.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #51 on: March 28, 2022, 08:33:21 PM »
I found out that you can make a boundaries script and attach it to objects to keep them within boundaries. I borrowed some code online for clamping boundaries and put it on my player.

It works for the left/right/top but not the bottom which I assume has to do with the scrolling background moving downwards. I think I'm just going to set a wall of fire at the bottom that is chasing the player or something.

This is the code I grabbed:

Code: [Select]
public class Boundaries : MonoBehaviour
{
    private Vector2 screenBounds;
    private float objectWidth;
    private float objectHeight;

    void Start()
    {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        objectWidth = transform.GetComponent<SpriteRenderer>().bounds.size.x / 2;
        objectHeight = transform.GetComponent<SpriteRenderer>().bounds.size.y / 2;
    }

    void LateUpdate()
    {
        Vector3 objectPosition = transform.position;
        objectPosition.x = Mathf.Clamp(objectPosition.x, -screenBounds.x + objectWidth, screenBounds.x - objectWidth);
        objectPosition.y = Mathf.Clamp(objectPosition.y, -screenBounds.y + objectHeight, screenBounds.y - objectHeight);
        transform.position = objectPosition;
    }
}

Is there an easy fix to boundary the bottom with a scrolling BG that moves downwards (I have a script on the BG image that scrolls down and loops it).

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #52 on: March 29, 2022, 02:17:02 PM »
If you just want to 'move' a BG image, you could just make it a texture and just scroll it?
It would then work with your bounds stuff if I understand you correctly, as it won't actually be moving anywhere, it will just look like it is.

https://docs.unity3d.com/ScriptReference/Material.SetTextureOffset.html

(this is also a pretty nice way of doing parallax scrolling in a 2D game)

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #53 on: March 29, 2022, 02:26:51 PM »
If you just want to 'move' a BG image, you could just make it a texture and just scroll it?
It would then work with your bounds stuff if I understand you correctly, as it won't actually be moving anywhere, it will just look like it is.

https://docs.unity3d.com/ScriptReference/Material.SetTextureOffset.html

(this is also a pretty nice way of doing parallax scrolling in a 2D game)

That's actually what I'm doing haha.

Yeah, I have no idea why the bounds doesn't work for the screen bottom. Because you are right. The scrolling BG is just a background texture moving and should have no effect with the actual camera and play zone. Very weird, but I don't really understand how clamping code works (it grabs your screen dimensions and then halves them? why? Shouldn't it grab your screen dimensions and then just set max X/Y as the max X/Y of your screen?).

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #54 on: March 29, 2022, 02:37:01 PM »
(it grabs your screen dimensions and then halves them? why? Shouldn't it grab your screen dimensions and then just set max X/Y as the max X/Y of your screen?).

its getting the data from the centre position, so keep in mind a bounding box of size 10 will look like

-5 -4 -3 -2 -1 0 1 2 3 4 5

on its X-axis, so your range is gonna be (-5,5) even though your size is 10

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #55 on: March 29, 2022, 03:00:40 PM »
Thanks, that makes sense.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #56 on: March 29, 2022, 10:51:59 PM »
I read some tutorials and picked up Aesprite on Steam. Made a 16x16 pixel enemy sprite with a 4 frame animation loop. Got it working in the game and then did a 4-5 frame death animation on hit that matched the enemy.

Then since I was figuring out animation, I imported the player death animation into Aesprite and edited the sprites into some other animation and then imported it back into Unity replacing the ship death animation. Yay.

Now when you hit something it looks less crappy, but I still don't like that the ship warps back to the initial start point when you die. I wish I had the time/skill to figure out how to make it respawn in place and just blink for the 2-3 sec invuln state. I could probably do the blink animation (just set it blank every other frame?), but I don't know how to code that change.

At this point I'm starting to get there. I need to figure out how to make a music loop for the first stage and figure out how to make a title and win screen and then I have a title screen, a stage with enemies, music, a win condition, a win screen and that's enough and then time to tidy up stage 2 with some unique features and new enemies/music. Doubt I'll have time for a stage 3 before turning in the project. So probably just 2 stages. 1 top-down free roam, 1 vertically scrolling.

Sprites are pretty fun. I have zero x 00000 art drawing skills and I still made a decent enemy that animates and looks ok moving around with my move script. My biggest problem with art is going to be that I don't know how to do shade/lighting to give a less flat/basic look. I just never took art courses to understand how things should look with lighting.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #57 on: March 30, 2022, 02:25:23 PM »
I still don't like that the ship warps back to the initial start point when you die. I wish I had the time/skill to figure out how to make it respawn in place and just blink for the 2-3 sec invuln state. I could probably do the blink animation (just set it blank every other frame?), but I don't know how to code that change.

The best way of doing this would be a coroutine, but lets do baby steps with shit you're familiar with already:
Code: [Select]

// lets declare some variables
int spawnCooldown=120;
bool spawnProtection=false;
Transform deathPos;
Renderer rend; // cache a reference to this in your Awake() method, because you're about to abuse the shit out of it

void OnDeath() // call this when ya die
{
     deathPos = transform.position;
     spawnProtection=true;
     spawnCooldown=120;
}

// on your respawn call, teleport the player to deathPos;

void Update() // lets put the rest of this shit in your update loop
{
     if (spawnProtection) // add this check to your takedamage call with a return, so if they have spawn protection enabled, no damage is done.
     // you might want to turn off collision too while its active...?
     {
          if (spawnCooldown <= 0) { rend=enabled=true; spawnprotection=false; return; }
     }
     spawnCooldown --; // this decreases this variable by 1; at 60fps, this will be 2 secs of invulnerability at a default value of 120
     if ((spawncooldown % 2) == 0) // this is a Modulo; its basically the 'remainder' after a division. In this case, if the cooldown timer is an odd number it wont run, if its even it will; ie it will turn the sprite on / off rapidly.
     {
           rend.enabled=true;
     }
     else { rend.enabled=false; }
}



Sprites are pretty fun. I have zero x 00000 art drawing skills and I still made a decent enemy that animates and looks ok moving around with my move script. My biggest problem with art is going to be that I don't know how to do shade/lighting to give a less flat/basic look. I just never took art courses to understand how things should look with lighting.

The good thing about pixelart is the skill ceiling is much lower than, say, hand drawn art, and also you don't have to get into the fucking wizardry shit people like 90s era Square were pulling off knowing about colour bleed and non-square pixels and shit on CRTs.
There are a bunch of good youtube videos on pixel art for newbies, and also a decent selection on twitter, which are usually espcially good as the pixelart is the tutorial;


this is the kind of 'doing shit on twitter for internet clout' I approve of  :wow

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #58 on: March 30, 2022, 03:32:51 PM »
Yep, excited to get more into the world of pixel art tutorials.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #59 on: March 30, 2022, 08:51:38 PM »
Ok, made a song in Bosca Ceoil, which was surprisingly made by Terry Cavanaugh (vvvvv, super hexagon, dicey dungeons). People recommended it as the best free song making software for PC.

It's good but it's missing some QoL stuff like autosaving your project. Lost my first hour and track when it saved absolutely nothing. :|

It's probably good for a start and I will save OFTEN, but may end up putting down money for FL Studio or Ableton Live at some point. Garage Band is supposed to be tops but I don't want to make stuff on my ipad, I want to make it on my PC with my mouse and KB.

Next up will be figuring out some splash screens. Probably will try to make one today before closing out for the day.



One issue is when I finally made a sorta entry level ok midi tune it doesn't fit my game at all and is like a chill visual novel at the beach tune  :lol
I figure I'll use it for the title track and try to make some stuff that fits my game more next.