#πŸ–ΌοΈβ”ƒ2d-tools

1 messages Β· Page 59 of 1

craggy kite
#

try to find another one tbh, brackeys is outdated and often not very well done in terms of longivity in a project+

hot fog
#

ok

dusky wagon
#

Okay sorry, wont mention you again. So I want to SmoothDamp the last velocity towards targetVelocity

craggy kite
dusky wagon
#

Where exactly am I doing that?

craggy kite
#

Oh was looking at the older one, sorry. So, do you have the most current version of your script somehow, to start from there?

dusky wagon
#

This is the latest part of the script but it doesnt really work at all

#

In there I tried to save the x velocity of a player that was added through the script this FixedUpdate in a float and damping the one that was added last one towards the target velocity

#

And then subtracting the velocity that was added last frame and adding the one added this frame at the end

#

But as soon as you hit a wall, the system breaks, as I assume it subtracts the velocity that was added last frame, but as you dont have it anymore since the wall is blocking the way it subtracts too much

#

At least thats what I think

craggy kite
dusky wagon
#

No it should stop

craggy kite
#

Okay I am confused πŸ˜„

#

Maybe someone else can enlighten this issue here

dusky wagon
#

Actually thinking about it what I says what I think causes the error probably doesnt make much sense

#

I dont really know why it breaks

#

I just know that the movement part for this old version here works, but for example a jump pad game object I have, cant add a force to the player, as it is damping down the entire x velocity

craggy kite
#

Why exactly do you want to damp the velocity of the temporary one, still trying to figure out your setup πŸ˜„

dusky wagon
#

In the newer try or in the old one?

craggy kite
#

in general, you want to damp the velocity of the player so it does not exceed anything or just damp the force it can get?

dusky wagon
#

I want to damp the force, so the player takes some time to reach his max speed and also to slow down again

#

So it doesnt feel like a robot

craggy kite
#

so why dont you just lerp the velocity of the player

dusky wagon
#

One second let me look up how that works in the unity scripting api

#

Okay so if I get it right, minimum would be the current velocity, the maximum the target velocity and tm_SmoothMovement?

craggy kite
#

lerp is going from vector a to b in the given time

dusky wagon
#

Ah

#

So the higher t the higher it will take?

craggy kite
#

if you use Time.deltaTime for example, and you multiply it by 2, it will go twice as fast, just try it out

dusky wagon
#

And will Time.deltaTime take one second?

craggy kite
#

its the timespan between frames / second, so if you have 60 frames, deltaTime will be 1/60 of a second I think

surreal panther
#

delta time workes on an always same amount of frames

craggy kite
craggy kite
dusky wagon
#

Yeah but Im still not exactly sure how that works, and since if you subtract something by time.deltaTime each frame, you subtract one every second, I thought it might take one

surreal panther
#

no sorry y actually wrote that up super badly

#

what y meant is that the fixed delta time works at the same speed on powerful or weak devices while delta time will give faster performances in a powerful device and slow performance on a weak device

dusky wagon
#

delta time is the time since the last frame passed, right?

compact knoll
#

Yes

surreal panther
#

yes

compact knoll
#

fixedDeltaTime is the time between FixedUpdate calls, but using Time.deltaTime in fixed update gives the same result as fixedDeltaTime. If you are doing calculations that need to be framer ate independent, use deltaTime

surreal panther
#

fixed delta time actually uses a fixed amount of time between each frame that's what it means

compact knoll
#

Yes, and if you are using that to attempt framerate independence in Update you are doing it wrong

craggy kite
#

Dont let you get confused πŸ˜„ fixedDeltaTime is the time for physics calculation which is on standard set to 50 calls per second I think, if you want to have performance independet stuff, use deltaTime, as it will change according to your renderer/calculated frames per second.

dusky wagon
#

Yeah I got that, but my main question is if it will take one second to get from a to b in a lerp method if t is delta time (or fixed delta time, doesnt matter since it is in fixed update)

craggy kite
#

you dont have to rely on delta time, you can use whatever timespan you want, you just gotta count it up somewhere.

craggy kite
#

Ah thats good, thanks boxfriend πŸ™‚ yeah, check that out

#

I just assume you dont want any specific point to start and end, you want to keep it lerping while the game is running, but thats just a thought

dusky wagon
#

Okay so I think I got it, if t is 1, it will go the full way, if its 0.5 only half and so on, right?

#

Okay, I can find a way to implement that, but does that help in any way with the original problem?

craggy kite
#

We were talking about the damping problem. You still gotta figure out what you wanna damp, but that way you can control the speed or rather the acceleration of the player instead of damping the force added to the player

dusky wagon
#

Okay Im going to work on i plementing that in a second, but I assume this way still wont work. Does anyone have an idea for a different way to make it, so that I only change the part of the velocity that was added by the movement and not anything else?

compact knoll
#

Am I crazy or are you just trying to get it to accelerate to a certain velocity then only increase velocity from this source if it's below your maximum velocity?

craggy kite
#

Not really, he is trying to damp the force added to the velocity, not the velocity itself, somehow

compact knoll
#

Because if that's the case, just use AddForce and stop applying force past your preferred maximum velocity

dusky wagon
#

I want to slowly accelerate the player to a certain speed, but makes it ignore any forces applied from another script

compact knoll
#

Use AddForce instead

craggy kite
dusky wagon
#

Oh sorry for being unclear

#

And I also want it to slow decelerate once you stopped moving

#

I think Addforce wont work on the deceleration, right? Or can should I somehoe add negative force?

compact knoll
#

This is exactly the perfect use of AddForce. Gimme a sec and I'll paste the code. I helped someone else figure this out a few days ago

#

set up your linear drag and stuff right and it will automatically reduce speed when not attempting to accelerate

snow willow
#

deceleration is just acceleration in the opposite direction

compact knoll
#
playerVelocity = new Vector3(horizontal, vertical, 0) * speed;

if (!((playerVelocity.x ^ rb.velocity.x) <= 0) && Mathf.Abs(rb.velocity.x) >= maxVelocityDelta)
{
    playerVelocity.x = 0;
}
if (!((playerVelocity.y ^ rb.velocity.y) <= 0) && Mathf.Abs(rb.velocity.y) >= maxVelocityDelta)
{
    playerVelocity.y = 0;
}

substitute your own variables of course, but this should get you what you want.

#

oh sorry, i should mention that they used the playerVelocity vector as the force applied

dusky wagon
#

What does the operator ^ do in an if statement?

compact knoll
#

it checks if the force being applied on the axis is opposite the current velocity and that current velocity is not greater than the maximum, if it is it sets the force applied to 0

craggy kite
#

never seen this in any equation, any docs about it? @compact knoll

dusky wagon
craggy kite
compact knoll
dusky wagon
#

Okay I would assume that since it is a sidescroller game with gravity, I only need the x part and then an AddForce line, correct?

craggy kite
#

ehm, sidescroller means x and y, not z

compact knoll
#

ah yeah. This was actually initially written for a 3d game and i just swapped the z with y without thinking you wouldn't be applying upward force with vertical input controls

dusky wagon
craggy kite
compact knoll
#

so you could set the y force to 0 and remove that second if statement and it should work as expected

craggy kite
#

lets say you jump and collide with a jumppad, it would add up the force, right?

compact knoll
#

it was specifically structured to allow outside forces to further impact velocity while preventing the player input from going over the maximum allotted movement velocity

dusky wagon
dusky wagon
craggy kite
compact knoll
dusky wagon
#

Okay first I need to get all the variables right.
So I assume:
-maxVelocityDelta should be a positive number that determines the maximum velocity the player can travel at.

-playerVelocity is the force that I add to the player each time the FixedUpdate get played.

-horizontal and vertical are numbers from -1 to 1 that are determined by the input and control the direction

-speed is the speed at which the object accelerates

Are all of these right?

compact knoll
#

looks right to me

dusky wagon
#

I get an error int he line with:
(playerVelocity.x ^ m_Rigidbody2D.velocity.x)
It say:
Operator '^' cannot be applied to operands of type 'float' and 'float'

#

And as far as I know, I didnt change anything except the name of the rigidbody variable

compact knoll
#

Show the full line just in case

dusky wagon
#

if (!((playerVelocity.x ^ m_Rigidbody2D.velocity.x) <= 0) && Mathf.Abs(m_Rigidbody2D.velocity.x) >= maxVelocityDelta)
            {
                playerVelocity.x = 0;
            }```
stoic moon
#

I have multiple empty gameobjects on an enemy that act as barrels and determine the bullet's direction, this is my current code to fire out of all of them(they're in a list of transforms so i don't need to make seperate gameObjects) private IEnumerator shootProjectile() { foreach (Transform barrel in barrels) { canFire = false; GameObject bullet = Instantiate(bulletObject, barrel.position, barrel.rotation) as GameObject; bullet.GetComponent<Projectile>().doesDespawn = true; yield return new WaitForSeconds(attackspeed); canFire = true; } }
Currently they fire all one at a time, how would i get them to fire all at once?

compact knoll
dusky wagon
#

What exactly does the if statement do? I thought I only need to check if the current added velocity is above the maximum velocity

compact knoll
#

Actually I saw a single comment on a stack overflow page saying it doesn't work for floats, so you can just cast them to ints in that section and it should work.
I also just discovered Mathf.Sign() so you could just compare the values from that

#

That also checks if you are attempting to go in the opposite direction because if you are at or over max velocity in one direction you wouldn't be able to attempt to go the other direction until you get below the maximum again

dusky wagon
#

Okay so I just cast them as ints?

compact knoll
#

Yeah, or you can do Mathf.Sign for each of them and check if the values are equal

compact knoll
dusky wagon
#

Okay so I played around with the settings and I cant find a good setting for the linear drag so that you dont slide a lot but also dont fall or walk extremely slow, can I also use AddForce for the deceleration?

compact knoll
#

Play with the mass a bit too. It's hard to get it just right but it is definitely doable.

#

You will also probably want to tweak your speed value a bit too since that will impact how much force is being supplied each frame

#

But with higher linear drag it will stop quicker, but you need to apply more force per frame to maintain the speed. With more mass you'll need more force to accelerate to your preferred speed

still tendon
#

Hey, so, I added two UI buttons, for left & right movement, and for some reason:
in 60FPS, when I move right, it's all normal and smooth, but when I move left, the character looks like he's stuttering
in 30FPS it looks normal no matter the direction

the way I make him move is if the left button is being held, speed is set to -1.0, and if the right button is held, speed it set to 1.0, if no button is held speed it 0.0 - after the speed is set, I set the velocity to speed * movementSpeed

to make things even more weird is then I test it on PC it's normal no matter the FPS and direction.

dusky wagon
#

I want the player to stop moving almost instantly, but Im afraid that making him have a high drag would make him not be pushed by my jump pad for example which only add a force once

dusky wagon
compact knoll
#

Angular drag is rotational drag. Linear drag is exactly what it sounds like

still tendon
crisp narwhal
#

how can i add friction (decelerate over time)

vocal condor
#

ie velocity * 0.10f would be a ten percent degradation

pale jasper
#

How would i make a code to swap between two character

crisp narwhal
# pale jasper How would i make a code to swap between two character

Not 100% sure but just an idea using public bools in 2 different scripts and making them true/false (whatever needed) once the thing to swap character occurs and have the movement/everything else in the code check if that character is the one being controlled (using the bool)

#

private void Update()
{
  if (char1)
  {
    //movement code
    //check for event that makes you change character
      -> make char2 from the other script true and char1 to false
  }
}

smth like this idk

pale jasper
#

So next thing... how can i set up movement for 2 different characters

crisp narwhal
#

again idk if my code example above would work but u would have 2 scripts, and 2 sprites

#

1 script per sprite

#

and the othe script would just be the same as the first one (the one above)

pale jasper
#

For example- One can run and crouch the other cant

crisp narwhal
#

but with char2 in the code

#
----SCRIPT 1 ON SPRITE 1----

public bool char1 = true;

private void Update()
{
  if (char1)
  {
    //movement code
    //check for event that makes you change character
      -> make char2 from the other script true and char1 to false
  }
}


----SCRIPT 2 ON SPRITE 2----

public bool char2 = true;

private void Update()
{
  if (char2)
  {
    //movement code
    //check for event that makes you change character
      -> make char1 from the other script true and char2 to false
  }
}
#

Again, im not sure if this is the way im just bouncing ideas around thats all

snow willow
#

Eh wouldn't it be easier to just use one script

#

put it on both objects

#

and enable/disable them as needed?

#

then you don't have duplicate code

fleet knot
#

Hello guys, i want to make area skill for my 2d player what should i use?

civic knot
#

Donno. My internet is so slow, I can't load the docs page. What does it say?

#

I've seen that page. I couldn't load the docs page.

#

Read what the docs say.

nova bear
#

How do I round a float

nova bear
#

I need help with something
I set my x position to either -6.5f or something over -6.5f, but when it gets set to -6.5f it actually gets set to -6.499999999f or something. Here's the code:
xSet(-6.5f + (Random.Range(0f, 12.5f) * Random.Range(0, 2)));

abstract olive
#

Yes, that's the nature of floats. They're rarely the exact number, and are at best "close enough".

#

This is why you never do an == comparison between two float values.

nova bear
#

ik

#

the solution to my code is just (transform.position.x - 0.01f) <= -6.5f

#

because if its less thats also fine

#

and its never initially less

#

yay it works now

flat imp
#

how would you check if something is colliding with a specific type of object?
like lets say you have a coin prefab, how would you check that the player is touching a coin and then delete the coin you are touching?

i know about OnTriggerEnter but it seems to only apply to "other" and not a specific kind of object

i know there is documentation and tutorials but thats where i learned the information i already know and im really struggling to understand it

#

and on the subject of collision
i found that rigidbodies arent preventing me from going into wall tiles, they just kinda push you out of the walls, making a weird vibrating screen

compact knoll
#

sounds like you probably want to enable continuous detection for the rigidbody, unless you are moving it using the transform in which case don't do that.
As for the collision, most people will generally put a check in their OnCollisionEnter or OnTriggerEnter to determine if the collision is with a certain kind of object. A lot of the time it's a check comparing the tag of the colliding object

compact knoll
flat imp
#

im sorry if im really struggling with unity... ive been using gamemaker studio for like 8 years and... honestly C# is really easy, its the functions of unity that really trip me up

compact knoll
#

modifying the transform.position ignores physics. move the rigidbody using MovePosition, AddForce, or change the velocity directly (of the 3, AddForce is the best option)

flat imp
#

im struggling to commit these things to long term memory
and also... can i just say how much it sucks to have so much experience but no knowledge to back it up

#

it makes every success seem so much smaller and every failure so much more dissapointing

compact knoll
#

it just takes time to get things right. it doesn't help when you get bad advice either (like moving the transform if you want physics to work properly). Just try to think of the failures as learning opportunities rather than just failures.
if you wanna post your movement code we could get that worked out to something that works better for your needs

flat imp
#

honestly its really late, hooking up my hard drive requires moving the laptop, and also unity and visual studio take a long time to load things

so... im sorry but i really cant do that right now

#

maybe tomorrow if i feel like trying

flat imp
#

honestly that guy was the first one here to not make me feel like an idiot

dense timber
#

Hey guys I, I recently started my very first unity game and I’m having one heck of a time getting a damage and health system to work properly. I tried following multiple tutorials but always something wrong with the code. I was wondering where I could find help or someone to walk me through it.

craggy kite
nova bear
#

question: How can I add 50 pngs to a script component together? Adding them all manually would be kind of messy.

#

actually I might still just make a public Sprite[] array

craggy kite
#

You can just lock the inspector and then select 50 pngs and add them

nova bear
#

now it'll take seconds

late viper
# nova bear

i wouldn't pollute the inspector like that, you should really do that in code

nova bear
#

how can I get 50 things from asset without dragging them there

#

also I can just hide it since public arrays are drop-down

late viper
#

Resources.Load

nova bear
#

ah i'll look into it later

#

but despite that i've decided those images are a waste of my hour

#

i'm going to use a shader to pixelate my sprite instead

#

these images came out in poor quality anyway

abstract grail
#

hey! does anyone have any code i can use to allow the player to move up down left and right with no jumping while the camera follows the player?

compact knoll
turbid heart
abstract grail
fluid vine
#

my buttons arent visible and not clickable when i build the game. does anyone know what the problem could be?

abstract grail
fluid vine
#

the problem is that it works just fine in my game preview

#

but not when i build it

#

which is weird because why would it do one thing just fine but the other same thing doesnt

fluid vine
#

no they are like right before the background screen

#

and they are fully functioning in the game preview in unity

#

but just not in the build

craggy kite
#

so you see everything from your scene besides the UI?

fluid vine
#

yeah

#

in the build yeah

craggy kite
#

can you share a screen of both?

fluid vine
#

uhhh sure

#

its a weird game be prepared

craggy kite
#

you got a null error in your scripts

fluid vine
#

and i thought the buttons were out of sight

#

wait

craggy kite
#

First fix those errors before building

fluid vine
#

yeah that just happened because i tried to fix it

#

uhhh

#

no thats from a delete script so it doesnt matter

craggy kite
#

can you put your gameview to a resolution 16:9?

#

and share that screen?

fluid vine
#

where do i do that

#

im really new sorry

craggy kite
#

go to game view, than on top left of that view, there is a resolution button

fluid vine
craggy kite
#

And already things are out of sight, right

fluid vine
#

yep

#

should i put them in the rigth space

craggy kite
#

thats your issue, your canvas is not adapting properly

fluid vine
#

ah

#

i hope this is gonna work

#

im gonna adjust the placement

craggy kite
#

you need to align your objects relatively, not absolutely

#

so instead of putting them 200px from left, you should put them for example 20% from the left, but how to do UI placement should be learned in a tutorial πŸ™‚ not a coding question for now then. Just look up some recent UI tutorials, they will explain it to you πŸ™‚

fluid vine
#

yeah the alignment doesnt have to be perfect, its a joke (as you can see from the screenshots) so the buttons just gotta work

#

got this rn

#

so thats better already

#

im gonna try to build it now

#

and see if it works

craggy kite
#

Alrighty πŸ™‚

fluid vine
#

still doesnt work

craggy kite
#

can you show the inspector of one button and the canvas component too?

fluid vine
#

from button

craggy kite
#

open up the recttransform component please πŸ˜„

fluid vine
#

canvas

#

button again

craggy kite
#

woah, okay, your z value is off πŸ˜„ can you put it to 0

fluid vine
#

that makes it go behind everything

#

should i put everything on 0 z

craggy kite
#

yeah, even if its a joke, it should be cleared up a bit πŸ˜„ put everything to z if possible, yes

fluid vine
#

i cant seem to change the position of the vanvas with the pink button

#

its all the way behind

craggy kite
#

The canvas is bound to your camera, thats okay. just put the buttons inside it to z 0

#

btw, you dont need separate canvases for every button

fluid vine
#

oh

#

does that matter?

#

or

#

not

#

oh and i put eveyrthing on z 0 but

craggy kite
#

it can also mess up the positioning. Just helps to clear things up too

fluid vine
#

now some things are overlapping

#

like, the background overlaps the floor

craggy kite
#

because you have more than one canvas, unity does not know which canvas is more important. If you just use one, unity will render in the hierarchy of your canvas

fluid vine
#

alright, im gonna try to

#

get the two buttons on one canvas

craggy kite
#

I know its a joke, but I am sure you want to learn how to use unity anyway, right? Why not start with a project you can mess up a little while trying out πŸ˜„

fluid vine
#

yea

#

i hope this is gonna work

#

ok i did it

#

i hope nothing bad happened

#

i cant see the buttons now tho,

#

i only see my character and the background

craggy kite
#

Okay, let me guide you

#
  1. select your button, first the left one
  2. click on that icon I put in the screenshot
  3. hold control and shift and click on the icon of the second screenshot.
#

if you select the right button, do the same but select the icon 2 to the right of the left one

#

Those buttons will anchor your buttons to the left and right side of the screen, no matter the width of the resolution

fluid vine
#

is it that one?

#

i cant find the exact same one

#

nevermind

#

forgot ctrl shift click

craggy kite
#

yep πŸ˜‰

fluid vine
#

ok did it

stoic moon
#

This is my script for instantiating particles, whenever I instantiate one the function runs fine until it gets to destroy, then it destroys both that particle and the bloodparticle object? I don't know where it would be causing that

#

nevermind my stop action was set to destroy

spark moth
#

Hey, when clicking a second time on a button, I would like to make it go back to its "Normal Color", is it possible through code (or editor), or should I use a toggle ? Thx !

dusky wagon
# compact knoll ```cs playerVelocity = new Vector3(horizontal, vertical, 0) * speed; if (!((pla...

After some experimenting with this, I pretty much got back to my original problem. I want to decelerate two different parts of the velocity at different speeds. I want to decelerate the players movement almost instantly as soon as the movement button isnt pressed anymore, but I want to decelerate other things, for example when the player is being pushed by a jump pad a lot more slowly. Does anyone have any idea how to do this?

stoic moon
#

This code doesn't do anything and spits out a warning that the animator is not animating?

#

This is my animator, with the bool isopen and the arrows corresponding to that

#

If I manually set it to true in the code, it works perfectly fine

rugged kestrel
#

Hi guys! I bumped into a small issue with my game. There is an enemy type called Spitter, it shoots acidballs. We control 2 players. Once taunted with the Clown character, the spitter turns left and so does the projectile it shoots. The problem is, that the acidball that already has been shot changes direction once I shoot with the cowboy again! Zombies should turn to the sound of gunfire, but the already shot projectile obviously shouldn't. Gotta attach a clip, hopefully it helps. Any fix on that?

Also the relevant code of the projectile:

https://paste.ofcode.org/dnRU96q66fxEs96QHpRUfw

worthy stump
craggy kite
#

Do you only flip the sprite?

#

and is the sprite a sheet with your enemy and the shots?

rugged kestrel
rugged kestrel
worthy stump
#

Presuming that you instantiate the acid ball, you could try moving logic for flipping the sprite out of update, and into "Start". This will set its orientation. On update you can then query the .flipx value in order to to your transform.translate

#

pseudocode:

{
 If targeted
  {
    Set FlipX correctly
  }
}

Update()
{
  If flipx
  {
    Traslate left
  }
Elses
{
  Translate right
}
}```
#

God that formatting is awful πŸ˜›

#

Doing it that way does mean that the acid ball won't be able to change direction at all, though (Assume thats how you want it)

rugged kestrel
worthy stump
#

No problem πŸ™‚

craggy kite
#

Well, are there animations in the animator ? @stoic moon

stoic moon
#

yes

craggy kite
#

and they are animating?

stoic moon
#

According to google it has something to do with prefabs as well

#

it plays the default animation when it loads in, the variables are set

craggy kite
#

well it says your animator is not animating, so you should select the object with the animator in it, open the animator view and check if something is happening

stoic moon
#

Just the default animation that i've set

#

then nothing happens

craggy kite
#

then it is not animating, so its a tru ewarning, it will still do your stuff, but just warn you, that nothing is happeningm because you are missing a translation to a new animation for example or a loop

stoic moon
#

found it

wild pivot
#

How can I change only the Z position of a game object

knotty barn
#

Copy the whole position, change Z, assign the position

distant pecan
dusky wagon
abstract olive
#

Do you not want to know when a player leaves a collider?

#

Maybe try explaining another way.

#

You want the player to be inside the box, but when they leave, you want the box to turn on? Is that it?

#

Well, if it has no collider, then you can't know when you're not touching it's collider. One way you could do it is to spawn it on the player with a trigger collider so that the player can move around it. Then use the alternative OnTriggerExit() to know when the player leaves. At that point, you can turn off isTrigger on it to "turn" it's collider back to solid.

#

Set the collider on the box to be IsTrigger. Do you know what trigger colliders are?

#

I don't really know what your ultimate goal is.

#

But if you make a collider a trigger, it will let rigidbodies pass through it. Ie, your player will not be blocked by it.

#

Of course, this would mean that you wouldn't be able to go back into it. But your ask is pretty vague so.

#

And I've explained it twice how to achieve it.

dapper shard
#

I want to collect all the tiles that the cyan lines intersect. I'm using a tilemap, and each large (see bold) square is a tile. How would I go about this in C#?

abstract olive
#

You check if it's the player that's leaving. Usually, you check the tag of the object which is leaving.

#

It's a built in MonoBehaviour function.

#

Sorry, I'm not going to do this for you. I've given you the steps to achieve what you want, but you'll have to do some research and learning on how to use those functions.

vocal condor
#

That's not how Unity messages work. I suggest Googling and watching a tutorial about collision/trigger detection. Your original question has already been answered. Your new request of code example wasn't accepted.

forest halo
#

dude youre just being rude

abstract olive
#

No memes

#

!warn 795025480649932800 Don't use ableist slurs. Don't cry if you're not getting help handed to you on a platter

barren orbitBOT
#

dynoSuccess asdfasdfasdadsfsadf#3129 has been warned.

stoic moon
#

I've updated my project to the most recent version, but my tilemap suddenly isnt effected my my global light and is just black? how can I fix this???

#

nevermind

#

turns out the sorting layer in my global light was reset

lean estuary
#

May want to turn off/on or recreate the light. Yea, component properties on light sometimes also being reset on some upgrades.

stoic moon
#

I have another issue, for some reason one of the objects i had hidden in the inspector I can't untick as hidden? its only that object other objects work fine

lean estuary
#

Toggle entire group visibility

stoic moon
#

Wierdly leaving the scene and coming back seems to have worked

frigid minnow
#

Just wanted to share what I've been making :]

frigid minnow
#

Good catch!

still tendon
#

how can i get the tile my raycast collides with?

lean estuary
#

@still tendon You can calculate it from the hit position accounting for cell size and converting to int Vector to access it.

#

(Depending on the tile anchor on tilemap itself might need to correct conversion to an int vector with an offset)

mellow sleet
#

hi i have a animation inside a prefab can someone tell me how i active them?
Animation.play();
didnt worked.
(C#)

lusty moss
#

alright so i dont know anything about coding but i am good at pixel art i want to make a little adventure rpg game to work on when im bored but like i said i dont know anything about coding is there any youtube videos or anything i can use to get started?

tall current
#

yes.

#

just look up something like "beginner Unity tutorial".

#

There's sooo many videos showing soo many ways of doing things on YouTube.

lusty moss
#

alright thanks

dense light
#

how can i go about taking a tile from a tilemap and using it as my player?

#

never done a 2d game before

rapid wagon
#

In Unity 2D, is there any way to check to see if an object is in camera view?

subtle vessel
#

this is an option

#

with an orthographic camera (which you're probably using in 2D) it is also pretty easy to calculate where the edges of the camera view are

#
Camera cam;
float camViewHalfHeight = cam.orthographicSize;
float camViewHalfWidth = camViewHalfHeight * cam.aspect;
float xMin = cam.transform.position.x - camViewHalfWidth;
float xMax = cam.transform.position.x + camViewHalfWidth;
float yMin = cam.transform.position.y - camViewHalfHeight;
float yMax = cam.transform.position.y + camViewHalfHeight;
#

you can compare the object's position to the edges of the camera's view and see if it is inside it

#

but that can get tricky if you care about the whole object, rather than just the center of the object

rapid wagon
#

Ok, thanks!

hoary ginkgo
#

Tips or link to a guide on saving variables of gameobjects inside of variable, then loading them back

#

Trying to set up a store, When I open my store, the gamesobjects inside of an array are active if the variable TrueOrFalse =1. If it doesn't = 1, it is set to false.

#

If you click purchase on an object, it sets the the truefalse variable to 0. I am trying to save that

dense light
#

what's the best way to setup 2d tile colliders?

#

i tried a tilemap collider but i think it's making my isgrounded behave weirdly

#

my player floats off the collider and idk y

subtle vessel
# hoary ginkgo Tips or link to a guide on saving variables of gameobjects inside of variable, t...

It depends on how much data you have. The general process of saving data out of your game and loading it back later is called "serialization" and "deserialization."

Here's an article that can help get you started.
https://naplandgames.com/blog/2016/11/27/saving-data-in-unity-3d-serialization-for-beginners/

hoary ginkgo
#

Oh I have started. Been trying to get this to work for about 4 weeks.

#

Thanks for the link

#

Havent seen that one

dense light
rapid wagon
#

For some reason, my Unity GameObject is showing up in Scene View but not in Game View. I can't do anything with the camera since it's pretty much fixed so that it'll follow the player, and it won't let me change anything. How do I fix this?

compact knoll
#

gonna need more info on that. Is it a sprite? is it somehow rendering behind another sprite? is your camera culling set up so that it will render that?

rapid wagon
#

It’s a sprite. It’s not rendering behind another sprite, I don’t think. The only thing it could be rendering behind is an empty GameObject that spawns it. I’m not sure how to set up the camera culling like that, but it’s fixed, so I couldn’t really mess with it.

#

Wait, I fixed the problem

last elm
#

Hey uh- I'm having problems with lighting tilemaps, can't tell if that belongs here

turbid heart
harsh silo
#

can someone help me with a script

harsh silo
#

?

harsh silo
#

Can anyone tell me why its just jumping without me pressing anything

#

nvm i fixed it

deep granite
#

Hi can someone help me out here? I'm trying to get an object to follow the mouse cursor around the screen, and when the cursor leaves the screen, the objects stays within the screen, where the cursor left off

#

This is my code for getting the object to stay within the screen and when I tried it, the object completely disappears.

supple junco
#

I'm trying to implement 2D Sonic-style physics using Unity's 2D components, and I've run into a bit of a wall. The physics values don't work like they should and the angle stuff is crazy broken: https://github.com/Candescence/Unity2D-Sonic-Physics

GitHub

An attempt at implementing classic Sonic the Hedgehog-style physics using Unity's 2D components, - GitHub - Candescence/Unity2D-Sonic-Physics: An attempt at implementing classic Sonic the H...

#

Unfortunately, the math is a bit beyond me, so I'm not sure what I'm doing wrong here.

deep granite
late viper
stoic moon
#

I'm trying to make a rotating enemy, and it works most of the time, but whenever my player walks into it it's movement breaks and it starts moving in really wierd directions? This function is being called in another script but that shouldn't effect anything

#

In another script that's attached to the object makes it so that it ignores all collisions with the player?

dusky wagon
#

Does the force added by the AddForce method change depending on the velocity of the object it is used on?

vocal condor
#

Either ways, this is all being added to your velocity. Which is the base whereas the force being added is the offset.

deep granite
#

@late viper wait u mean, writing print(viewPos); at the end of the code right?

#

how did the object go outside the boundary?

dusky wagon
#

And the only reason I could imagine was, that AddForce changes the velocity applied based on the current velocity of the object, since walking normally works fine

worthy stump
# harsh silo nvm i fixed it

Just providing the answer for anyone else who's wondering. The "If" statement within the update loop was terminated by a semicolon. When this happens, the body of the statement will be executed regardless of whether the condition is true or not. "Ifs" should never really be followed by semicolons.

still tendon
#

Does anyone has a script for a gun

#

In 2d

grand coral
# still tendon Does anyone has a script for a gun

two things: first, you have to be much more specific to get the answer you want. second, don't just steal scripts from others when you could easily make them yourself. outline all the things you want your gun to do and go through them one by one yourself. if there's a small step you need help with along the way, you can ask that here.

turbid heart
#

<@&502884371011731486> here too

waxen chasm
#

Hello, i got error Script Error: OnTriggerEnter2D

The code:

private void OnTriggerEnter2D (Collider collision)```
#

please help :(

compact knoll
#

what is the full error?

waxen chasm
#

Only showing that

#

The message parameter has to be of type: Collider2D

compact knoll
#

so make the parameter a Collider2D.

tall current
#

not OnTriggerEnter

#

therefore the return must be Collider2D

waxen chasm
#

Oh, wait let me do it

#

it's not error anymore thank you!
but the score not counted

#

(making flappy bird)

compact knoll
#

that's not relevant to the issue you posted. Let's focus on that first. Did you fix the Collider2D issue?

waxen chasm
#

Yes

#

I did

compact knoll
#

great! now show more code and explain what you expect to happen, and what is actually happening

waxen chasm
#

wait

tall current
#

there are more problems?

waxen chasm
compact knoll
#

aren't there always? lmao

waxen chasm
#

wait i send the code

compact knoll
waxen chasm
#
using UnityEngine.UI;

public class playerMovement : MonoBehaviour {
    Rigidbody2D Rb;
    public float jumpForce;

    float score;
    public Text scoreTxt;
    void Start () {
        Rb = GetComponent<Rigidbody2D>();        
    }
    
    // Update is called once per frame
    void Update () {

        scoreTxt.text = "" + score;    
    if (Input.GetMouseButtonDown(0))
        {
        Rb.velocity = Vector2.up * jumpForce;
        }    
    }

    private void OnTriggerEnter(Collider collision)
    {
    
        if (collision.gameObject.tag=="point")
    {
        score++;
        }
    }
}
wild pivot
#
SpriteRenderer.color = 727272;```I want to change the color of a game object using a script, and I want to use a specific hexadecimal but unity won't allow me, how can I do this?
waxen chasm
#

and i also tag and point the trigger object

compact knoll
#

you also didn't fix the issue from before

waxen chasm
#

i'm a beginner, could you tell how to use CompareTag()

waxen chasm
compact knoll
#

oh i see what you did, you changed from OnTriggerEnter2D to OnTriggerEnter. You need to use the 2D version if you are using 2D

waxen chasm
compact knoll
waxen chasm
#

ok i did add them again then?

#

how to add parameter 😦

waxen chasm
#

sorry, i am a beginner

#

alright

compact knoll
# waxen chasm ok i did add them again then?

you should seriously consider some basic C# tutorials before even thinking about continuing with Unity.
But you also have the word Collider in your script exactly one time. Change that to Collider2D

waxen chasm
#

Ohh i solve them all...

#

thank you

#

now one more issue's, the text so bad quality

compact knoll
#

use TextMeshPro instead of regular Text objects

waxen chasm
#

ok, thank you for helping

wild pivot
#
SpriteRenderer.color = new Color(0.4, 0.4, 0.4);

I have this in my script but I am getting an error that says "error CS1503: Argument 3: cannot convert from 'double' to 'float' " how can I fix this?

north grail
#

new Color(0.4f, 0.4f, 0.4f);

#

The 'f' denotes float

wild pivot
dusky wagon
#

Im having some problems with my player movement.
Player-Movement-Code:

layerVelocity = new Vector3(move, 0) * m_AccelerationSpeed;

            if (!((Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)) <= 0) && Mathf.Abs(m_Rigidbody2D.velocity.x) >= m_MaxSpeed)
            {
                
                playerVelocity.x = 0;


            }

Code for making the player stay on a moving platform when that one parents the players transform:

controller.m_Rigidbody2D.velocity += transform.parent.gameObject.GetComponent<VelocityFriction>().rb.velocity;

Whenever the player moves with the platform that is applying friction to it, he is extremely fast. Even though the parent object only has a velocity of 2 and the child one has a velocity of 8, the player gets launched at a velocity of up to 40. When the player moves in the opposite direction of the parent object it is extremely slow and has a lot lower velocity than it would normally have. Does anyone have an idea why and how I could fix it?

worthy stump
dusky wagon
#

Yes and the movement works so far, it just launches you when you walk on the moving platform

worthy stump
#

Could you write out in words what you want that if statement to do?

ancient path
#

Why can’t you parent the player?

compact knoll
compact knoll
dusky wagon
#

Oh right I confused it with python and tried int(and then the value here), but that didnt work, so I assumed you have to do it with the convert function

dusky wagon
worthy stump
dusky wagon
#

It might be because as soon as the player starts moving, the x velocity doesnt get set to 0 anymore and the two velocities stack together

#

Altough I dont see hpw that could case velocities of 20 or 40, And the weird thing is, that it is exactly 20 or 40

compact knoll
worthy stump
#

Im not sure it is, feel free to correct me though. I think if you wanted to do what you described you'd need to do:

if ((velA <=0) ^ (velB <=0))

I think what you wrote is doing a boolean operation on VelA XOR VelB (Which yeilds true or false, 1 or 0) and then comparing the result of that using <= 0

compact knoll
#

i assure you that is is working as i intended it to

worthy stump
#

Can you walk me through it?

#

Lets break it down:

#

(!((Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)) <= 0)

(Convert.ToInt32(playerVelocity.x) ^ Convert.ToInt32(m_Rigidbody2D.velocity.x)

This is a boolean operation, so will evaluate to True or False

Which means the above becomes:
(!((True/False) <= 0))

#

So i guess if one of the velocities is negative, the boolean operation will treat it as a zero. But that means that a zero velocity is also treated in the same way. So your resulting conditions in the game would be that the condition evaluates to true if one velocity is positive, and the other is either zero or negative

#

But then I'm confused why the result of that is compared using <=0 rather than just == true/false, or omitting that entirely

pseudo moon
#

Hey I was wondering if bolt support's 2d

real pilot
#

Why would you use Bolt?

vocal condor
#

Including after adding forces.

#

Chances are, you're doing a little extra or not doing something when moving. Best just assume nothing's really working and actually debugging everywhere you're modifying the rb's velocity.

hoary ginkgo
#

I am trying to save changes made to my store. 4 weeks of screwing with this, I am about to scrap the idea.

#

This bit of code is my shop template for my different shop items

#

This code is the code that loads my panels(shop items into the store)

#

This code is where the items should be saved after being purchaseed

#

This is the playerdata script

#

This is the save system

#

This is the initial scene without trying to load the save data. No save data yet

#

You can see the isactive bool is active so therefore the panel is active

#

This image the basketball has been purchased.

#

Setting the bool t false

worthy stump
#

And whats the issue?

hoary ginkgo
#

Upon leaving the scene or exiting the game, the bool isActive will not save or load

worthy stump
#

Ok, lets have a look

hoary ginkgo
#

So basically when I leave and come back all items are set to true again. I only want the player to be able to purchase once

worthy stump
#

Did you say you havent set up save data yet?

hoary ginkgo
#

This is just where I am at right now, I have tried changing stuff in playerdata all sorts of way

#

I have tried saving on awake to create the file inside of shopmanger

worthy stump
#

Try putting
[SerializeField]

Before your boolean flags

hoary ginkgo
#

Sorry, Not sure what you mean.

#

Which script

worthy stump
#

In Playerdata

#
public bool[] blah;```
#

Not sure if it works with arrays though

#

Oh sorry, you already flagged the class as serializable

hoary ginkgo
#

Right

#

I assume it has something to do with the way I am pullingn data in playerdata though

worthy stump
#

Are you actually calling your save function anywhere?

#

After purchase item

hoary ginkgo
#

Yes, I call it on shopmanger under purchaseitem

#

SaveSystem.SavePlayer(this);

worthy stump
#

I presume that the save function is actually being called correctly, yes?

hoary ginkgo
#

NullReferenceException: Object reference not set to an instance of an object
PlayerData..ctor (ShopManager shop) (at Assets/Scripts/PlayerData.cs:23)
SaveSystem.SavePlayer (ShopManager shop) (at Assets/Scripts/SaveSystem.cs:18)
ShopManager.PurchaseItem (System.Int32 btnNo) (at Assets/Scripts/ShopManager.cs:63)
UnityEngine.Events.InvokableCall1[T1].Invoke (T1 args0) (at <cfc1ad890650411e946cff2e6f276711>:0) UnityEngine.Events.CachedInvokableCall1[T].Invoke (System.Object[] args) (at <cfc1ad890650411e946cff2e6f276711>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <cfc1ad890650411e946cff2e6f276711>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:68)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:110)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:262)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:385)

worthy stump
#

Execution errors?

#

When does that occur?

hoary ginkgo
#

When I click the purchase item button

worthy stump
#

Ok, well this is probably why it isnt working, haha

hoary ginkgo
#

I assume it is happening when trying to save

worthy stump
#

Double click on the NullReferenceException, where does it take you?

hoary ginkgo
#

PlayerData line 23

vocal condor
#

Should be like 23 of the player data as suggested by the stacktrace.

worthy stump
#

Which one is that? No line numbers on the screenshot πŸ˜›

hoary ginkgo
#

isActive[i] = shop.shopPanels[i].isActive;

worthy stump
#

I'd guess shop is null

#

Could be the panels though

vocal condor
#

Likely not since it's a parameter passed to the function. Likely panel

#

It could be though (shop) if null was simply passed in πŸ€·β€β™‚οΈ

worthy stump
#

Yea, hard to follow a stack trace via screenshots without class names πŸ˜‚

#

@hoary ginkgo wanna stream it? Ill walk through it with you

hoary ginkgo
#

Yes

#

Would be great

vocal condor
#

Or isActive could be null as well

worthy stump
#

Cool, just send me a dm

dusky wagon
still tendon
#

can u help me understanding this prints pls?

#
print(hit.point + v * 0.5f);
print(grid.WorldToCell(hit.point + v * 0.5f));
print(grid.GetCellCenterWorld(grid.WorldToCell(hit.point)));```
#

hit is a RaycastHit2D

#

in this case v is (0,-1) i think, a ray going down

#

yeah, so original hit is at (0.5, 6)

#

so if im not wrong, world coordinates (0.5, 5.5) belong to the cell (0, 5), right?

#

but, why is the center that?

#

shouldnt the center be 0.5, 5.5?

#

oh my bad

#

i am forgeting the +v*0.5 on the cell center

#

so, from all those things, what do i need to give setTile?

vocal condor
#

The actual value doesn't matter much other than a possible pattern. As for the code snippet you've provided before, the first isn't relative to RB2d velocity or force (they're working with velocity variables that I'm assuming you're going to be applying to velocity eventually) and the second illustrates that your adding extra velocity to rb but we aren't aware how often or the values before/after.

#

Identifying when abnormality occurs will allow you to pin point the issue.

dusky wagon
#

Im running both these blocks of codes in fixed updates and the abnormality seems to happen between these fixed update calls

vocal condor
#

When specifically?

#

You aren't providing enough information for us; I know it's right in front of you but we cannot see when or how often you're modifying velocity.

dusky wagon
#

Okay I will try to provide more information, but Im really not feeling well right now so I will do it as soon as I get better

#

Thanks for the help so far!

still tendon
#

if i have a tile map with object that can be destroyed, should those objects be tiles too?

weak sinew
#

Is there a way to increase a textures sizes on a tile-map?

still tendon
#

yeah

#

pixels per unit

#

go to the sprite of the tile, and change pixels per unit

weak sinew
#

alright

twilit osprey
#

does anybody know how to fix UI buttons not working. they are interactable and yes i have an event system. idk whats wrong here. PLS HELP

still tendon
#

when u are making a 2d tilemap, and it will have destructible object, should these object be part of the tilemap too?

languid lily
harsh silo
#

Does anyone know a good tutorial on how to make enemies.

still tendon
#

Does anybody know any camera scripts/Cinemachine things that can allow me to limit the view range of my player?

#

like, i dont want players on larger screens to be able to see further

grand coral
grand coral
honest python
#

weird question

#

but

#

how do I display this in unity

#

(⸌﹏⸍)

#

cuz

#

it doesn't have the "⸌" and "⸍"

rapid wagon
#

My animations keep getting stuck and looping even after I release any button, where it's supposed to play the idle animation. It didn't do this until this morning. I am not using animation transitions. Can someone help?

grand coral
honest python
#

it did not

#

those characters did not show up in the textbox

grand coral
#

make sure you are using a font that supports those characters, that could be the issue

#

you shouldn't need them anyway, if you really do then you can use an image

grand coral
rapid wagon
grand coral
#

oh huh i see

#

well if you're not using any transitions maybe it's just never switching to the idle animation

#

are you switching to idle using another method than transitions?

rapid wagon
#

I fixed it

#

I basically accidentally put < somewhere on a timer when it should've been <=

sudden oar
#

does anyone know of a good tutorial that not only goes over 2d rigging, but also how to make a full walk cycle so that my player actually moves rather than just animates? A lot of tutorials are great at showing inverse kinematics, and the actual rigging/weight painting process, but I have no idea how to actually make a character walk with the steps that he's taking

snow willow
#

so just like

#

makee the keyframes and match with each reeference image

sudden oar
#

that's great, but I might not have worded that correctly. It's not a matter of making it look like it's walking, it's a matter of actually getting it to move

snow willow
#

worked pretty well for my first time

snow willow
sudden oar
#

unless the animator can make the character's transform position change, no

snow willow
#

usually you use other things to actually move it

#

like a Rigidbody or CharacterController

sudden oar
#

...

#

it's those other things that I don't understand

#

that's why I said no

snow willow
#

You asked about 2D rigging

#

so I assumed you were asking an animation question

sudden oar
#

oh

snow willow
#

moving the character is completely unrelated to rigging or animation.

sudden oar
#

well that's kind of the problem, tutorials always go straight to animation and nothing else

#

how would you sync the animation with the movement speed?

snow willow
sudden oar
#

hmmm...

#

I could give that a try

snow willow
#

sometimes play with a multiplier a little bit until the animation matches up with the actual movement speed properly

#

and then you're good to go

sudden oar
#

and multiply it when the character moves faster or slower

#

ok, thanks! I'll give it a try

snow willow
sudden oar
#

looks cool!

fleet knot
#

Hello Community, I wan't to ask something,how to make enemy drop item but the position is random(near dead enemy) on 2D games? and i am using for loop to spawn item but it spawn on the same position

compact knoll
fleet knot
compact knoll
#

you totally could. To figure out how to do that, break it down into steps:

  1. Instantiate at enemy position
  2. find desired end position
  3. move the object to the desired position
fleet knot
#

void dropItems(){
GameObject go = Instantiate(gameObject , position // i put move stament here? , Quaternion.identify)
}

compact knoll
#

nope, you would need to move it after you instantiate it if you want it to appear at the enemy position then move to another position

fleet knot
#

ok dude i'll try it thanks again

woeful sentinel
compact knoll
compact knoll
#

they did get it to work? but then they decided to do something different by having it move from the enemy position. are you just not reading the messages or what?

woeful sentinel
#

take your time

compact knoll
#

they initially wanted to spawn it at a random position offset from the enemy position. I helped them figure that out, then they decided they want it to pop out from the enemy, so i told them how they could do that.

woeful sentinel
#

πŸ‘€

compact knoll
#

am i missing something from the conversation i had?

#

or are you somehow implying that using your code will somehow make the item appear at the enemy's position and move to the offset position?

fleet knot
uneven stream
#

Im getting this error NullReferenceException: Object reference not set to an instance of an object
In the following code:

            _segments[i].position = _segments[i - 1].position;
        }```
#

I checked it and it's ok in vs code, no errors. I went to unity and appears this error and my entire game freezes.

turbid heart
uneven stream
#

NullReferenceException: Object reference not set to an instance of an object Snake.FixedUpdate () (at Assets/Scripts/Snake.cs:32)

#
    {

        for (int i = _segments.Count - 1; i > 0; i--) {
            _segments[i].position = _segments[i - 1].position;
        }

        this.transform.position = new Vector3(
            Mathf.Round(this.transform.position.x) + _direction.x,
            Mathf.Round(this.transform.position.y) + _direction.y,
            0.0f
        );
    }```
This is the code that refers to the error.
turbid heart
uneven stream
#
for (int i = _segments.Count - 1; i > 0; i--) {```
turbid heart
uneven stream
#

how can i fix it

turbid heart
#

is your _segments a List? make sure you've initialised or assigned to it

#

you can't access the .Count property of something that's null, so.. make it not null

uneven stream
#
7     private List<Transform> _segments;```
turbid heart
uneven stream
#

ok i just fixed it

#

a letter missing

turbid heart
#

really? damn

#

can you take a picture of your IDE please

#

your Visual Studio code

#

have you set it up properly to have intellisense?

#

when you type Debug. does it suggest Log?

uneven stream
#

was

private void Star()
    {
        _segments = new List<Transform>();
        _segments.Add(this.transform);
    }```
fixed
```cs
private void Start()
    {
        _segments = new List<Transform>();
        _segments.Add(this.transform);
    }```
turbid heart
#

wow, okay

uneven stream
#

i don't payed attention

#

and put star accidentally

#

well, thanks

uneven stream
#

is that bad?

turbid heart
#

if you set it up properly, you'd get autocomplete, suggestions, and typos in your code would be underlined

#

for that you'll need to confirm if you're using Visual Studio Code or Visual Studio Community

uneven stream
#

intellisense works fine

#

but not with debug

#

i will check whats wrong

turbid heart
#

i personally dont know about Visual Studio Code myself, it's just how I usually ask people to test

uneven stream
#

oh ok

#

btw im using the blue vs not the purple one

#

one thing more it's vs better than vs code?

turbid heart
#

blue vs is VSCode

#

VSCode is lighter weight than VS, but VS is easier to set up

chrome grove
#

Is there an easy way to setup a Tile Rule (Or something similar) where I can do a Checkerboard pattern?

dusky wagon
#

Whats a good way to make a rail system for a moving platform? I want to make some rule tiles that let me place a rail on a tile map. Then if you place a moving platform on the rail, the platform follows the different parts of the rail into the direction the lead to. I already have a system that makes the platform follow each on of the transforms of an array until it reaches it, then switches to the next one, but I am not sure how I could configure that system to work on a rail

#

I was also not able to find a tutorial on this online

stoic moon
#

This is my line of sight code, with the layermask set to everything but the enemy layer(all objects with this script have the enemy layer), but suddenly enemies now block it? I'm not sure what I changed to make this happen, but I'm sure its not with the variables. How van i fix this?

#

even setting the layer to ignore raycast does nothing, the enemies still block each other

#

Traced the issue to a gameobject as a child of each enemy, but it's just a trigger object with another layer set on it? Somehow that's blocking my raycasts

snow willow
stoic moon
#

Managed to find a solution to the problem

snow willow
dusky wagon
solar thicket
#

you want to turn off root animation, in the animator iirc

#

alternately, if you are making the animation in unity (and not importing it from somewhere), you can just delete any keyframes on the position

worthy stump
#

iirc = if i recall correctly πŸ˜›

shy blaze
#

how can i add offset to object relative to rotation??

chrome grove
silver heron
#

then you can also add a grid

still tendon
#

does duplicating my project and putting it somewhere on my pc a way to back up my project? Theres a crazy storm coming towards my house. would like to have a backup

worthy stump
#

At the very least, upload a zip folder of your project to google docs or similar

still tendon
#

damaged by an outage?

#

or lightning

worthy stump
#

Your project is stored on your computer's backing storage. If that physical component becomes damage, or corrupted, everything stored on it will become inaccessible

#

Imagine it like this, if you had a piece of paper with your code on it, and your printed out another piece of paper for a backup, put them both somewhere in your house and then your house burned down, you'd still lose everything

#

But if you took the printed copy and put it in your neighbours house, it would be OK

#

In this case, the internet is your neighbors house

still tendon
#

ok

#

Would it still help though if my pc shut off because of no power and I was on that project. I hear stories about that happening and peoples project getting corrupted

#

or is it the same thing

#

@worthy stump

worthy stump
#

That can happen

#

However in that case, if you had made a backup copy that was stored somewhere else on your computer (as you suggested) the copy would not be corrupted, only the project that was open at the time

still tendon
#

ok

#

thank you for your help

#

also cool profile pic

worthy stump
#

thanks πŸ˜›

pale tide
#

Is there a way to make all childs of a certain object in the editor force to have a script?

chrome grove
silver heron
chrome grove
silver heron
chrome grove
#

Right I understand how to go about doing a checkerboard pattern via code, but I'd rather build it out ahead of time via a Tilemap rule or something similar.

silver heron
#

general i'd say unless its a static object that wont ever change you'll probably need to code but otherwise you should be able to just store it as a prefab

celest drum
#

how do you have multiple Box Colliders on a game Object?

#

like for example if i want one collider for actual physics collisions, and another for checking distance or something?

fervent otter
#

Add it to a child gameobject @celest drum If those objects don't handle the collision/trigger the event will bubble up to the parent.

still tendon
#

is it normal that the pixel perfect camera makes moving objects stutter in a kind of way?

fervent otter
#

What version unity are you using @still tendon

still tendon
#

2020.3.01f

#

@fervent otter

fervent otter
#

Supposedly has been officially fixed in 2021

still tendon
#

Can I change the version on a unity project

fervent otter
#

Yeah in Unity Hub you can pick whatever versions you have installed

still tendon
#

is there a chance to corrupt?@fervent otter

fervent otter
#

I've never heard of it.

#

I mean probably

#

But I wouldn't worry about it

#

You should probably push all your changes before updating anyway

still tendon
#

push all my changes?

fervent otter
#

You might want to consider keeping your projects on github

#

in case something goes wrong

still tendon
#

Ok

fervent otter
#

like if your hdd dies or something

#

and takes all your work with it

still tendon
#

ok I'll look into that

#

thanks for the help πŸ™‚

strange cove
#

Ive been trying to figure this out for a while but couldnt does anyone know why when i click a crate and it changes my sprite to the other one my player goes in the ground? heres the code: https://pastebin.com/a6wnHL3J

faint iron
#

ok apparently i need someone to help, that my movement results in the left image (sharp movement, and the tip of the trail is not like a triangle, and i want the results to be the right illustration instead. how to do this?

#

my script:

    public Vector3 movleft;
    public Vector3 movright;
    public Vector3 movup;
    public Vector3 movdown;
    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            transform.position = transform.position + movright;

        }
        if(Input.GetKey(KeyCode.A))
        {
            transform.position = transform.position + movleft;

        }
        if(Input.GetKey(KeyCode.W))
        {
            transform.position = transform.position + movup;
        }
        if(Input.GetKey(KeyCode.S))
        {
            transform.position = transform.position + movdown;
        }
    }
}
slim crescent
#

I have a 2D platformer where the player's character is a robot that can change out its body parts. Different body parts might have different "use" animations. How do I have each body part tell the player's animation controller what the "use" animation should look like? Should each body part have its own controller? I'm pretty new to this area so I don't understand animation vs animation clip and a lot of stuff like that.

slim crescent
faint iron
dusky wagon
#

How can I recreate the Vector2.MoveTowards method with rigidbody velocity? I already have a script, that sets the velocity of an object to move towards another one, but I want to include the feature that it doesn't go over the object, but stops as soon as it hits it. I tried making it stop as soon as it is in a certain distance of the object, but it isn't frame independent. If the frame rate is too low, it doesn't catch the point where it is close enough to the object and just shoots over it.

slim crescent
#

use rigidbody.velocity instead of setting position directly

slim crescent
#

you're right though he probably wants the true linear nature

#
if(timeElapsed < lerpDuration)
{
  rb.velocity = Vector3.Lerp(lastDirection, newDirection, (timeElapsed += Time.deltaTime) / lerpDuration) * speed;
}
slim crescent
# faint iron ok thank you
{
  rb.velocity = Vector3.Lerp(lastDirection, newDirection, (timeElapsed += Time.deltaTime) / lerpDuration) * speed;
}```
please use this instead
faint iron
#

okay

still tendon
#

is there a way to remove a script from an object ?

abstract olive
still tendon
abstract olive
#

Yes, you pass in the component. A script is just a component.

#

Destroy (GetComponent <MyComponent>());

idle kite
#

Hey! πŸ™‚
So, I have a pixel art game and have some zoom issues. it seems that the max zoom I can get is pretty small. I would like further zoom.

I've read Unity's documentation and it suggested to use this function to get the camera zoom right:
var camSize = (Screen.height / (zoom * pixelSize)) * 0.5f;

zoom is from 1 to ∞ where 1 is max zoom, and pixelSize is our assets size (in our case, 128px).

As mentioned, 1 is pretty small. Any suggestions? should we maybe use smaller assets?

dull radish
#

why are my sprites doing this when colliding?

#

sorry if this is the wrong channel to post this

turbid heart
dull radish
#

getting on top of each other i mean

#

it looks weird

turbid heart
#

You probably need to adjust their sorting order in sprite renderer

dull radish
#

ohhh ic

#

i'll try that

main hemlock
#

Hello. I am trying to make a bit of a logic 2d game and I want to have 3 floor colors and 3 lever with the same colors as the floor.

    {
        if (collision.gameObject.CompareTag("Lever") && useHand == true)
        {
            if (collision.gameObject.name == "LeverRed")
            {
                redFloor.gameObject.SetActive(false);
                print("red floor gone");
            } 

            if (collision.gameObject.name == "LeverGreen")
            {
                greenFloor.gameObject.SetActive(false);
                print("green floor gone");
            }

            if (collision.gameObject.name == "LeverBlue")
            {
                blueFloor.gameObject.SetActive(false);
                print("blue floor gone");
            }
        }
    }```
This behaves really oddly as I sometimes manage to destroy one floor with the lever, but afterwards when my player collides with another lever, that lever becomes inactive. There is also a situation where my lever doesn't work. It seems random. Any idea why that would happen?
#

Okay, actually not that random. I always manage to destroy the red floor and the red lever is the only lever that doesn't disappear.

#

Nevermind, I resolved the issue. Had the levers inside my player component (inspector) instead of the floors by mistake (I am really tired). But if there is anything I should fix in that code, please let me know.

dusk hatch
snow willow
#

invoke takes the name of a function to run

dusk hatch
#

oh

#

I tried to make a separate function but the collider, "en" wouldn't work in it's own function

snow willow
#

you should use a coroutine

#

they're much more flexible

dusk hatch
#

okay, thanks ill try to find out what that is

snow willow
#

@dusk hatch Something like this:

IEnumerator SetMoveSpeedAfterDelay(Enemy enemy, float speed, float delay) {
  yield return new WaitForSeconds(delay);
  enemy.moveSpeed = speed;
}```
And to start it:
```cs
StartCoroutine(SetMoveSpeedAfterDelay(en, 5, 3));```
dusk hatch
#

oh wow thanks!

blissful sundial
#

anyone know how i could make a game object follow a predetermined path ingame?

unborn sundial
#

@blissful sundial I'm aware of two things that might help. Unity Timeline (package), and Animation Curves, but I haven't used either.

#

you could also do it in script/code obviously

blissful sundial
#

im trying to script it atm

craggy kite
blissful sundial
#

i tried scripting a game object following a path but it isnt moving, could be some oversight but i cant tell whats wrong NPCMechanicShrug

#

i have an array attached to my path parent (it has the path joints as children and those joints are all in that array), and a script attached to the object: https://paste.mod.gg/lozigipoyi.csharp

craggy kite
#

Is it 2D?

blissful sundial
#

ye

craggy kite
#

What is your movespeed?

blissful sundial
#

7f

craggy kite
#

its public, so did you accidentally change it to 0 or something in the inspector?

blissful sundial
#

hm, lemme check

#

ah i see, it didnt update

#

i had it at 0 and saved it, then changed it to 7 and unity didnt update the value

craggy kite
#

if its set in public inspector once, it will rely on the inspector, no matter what you do in code in the public var line πŸ™‚ @blissful sundial

blissful sundial
#

ah thats why

#

thanks for the info πŸ‘

snow willow
#

BTW you can look into Cinemachine's dolly cart component

#

You can edit the freeform path in scene view and the dolly cart can be scripted to follow the path

lament rivet
#

I can’t see the textures on my 2D game

#

I tried to apply a red texture

#

and it’s invisible

#

why won’t my texture work

craggy kite
#

we need some more info, where do you apply them, is the alpha of the color to 1?

lament rivet
craggy kite
lament rivet
#

there really isn’t any coding involved

#

Just a circle that is visible with a line texture but not with a red texture

dusk hatch
snow willow
dusk hatch
#

thanks it works better now, but there's still a small problem, the enemy is supposed to slow down, then after 3 seconds, get up to 5 speed again, but it doesn't gain back it's speed at all

snow willow
#

It's pretty straightforward

#

Just wait another 3 seconds in the coroutine and set it back

dusk hatch
#

hmm okay

#

not sure why it aint workin

snow willow
#

That stops the coroutine as well

dusk hatch
#

yeah

#

I found out what to do eventually

#

infact the game I was making is now done!

#

so thanks for your help, people like you are really awesome

snow willow
#

Np happy coding

still tendon
#

is there a way to make a collider along a camera?

still tendon
#

i don't want any objects to leave the view of the camera

#

instead they'll bounce off

snow willow
#

Place box colliders at the edge of the camera view

still tendon
#

ok

#

now everything just falls

#

should i have used 4 different edge colliders

solar thicket
# still tendon ok

colliders only push things out of them, they don't keep things in them

still tendon
#

why?

abstract olive
#

Check your console for any compiler errors.

still tendon
snow willow
#

I see 466 errors - I bet one or more of those will stick around after you press clear and those will be the ones you need to fix

still tendon
#

?? i hit it

snow willow
# still tendon

go into package manager, make sure all your packages are up to date. Then delete your library folder and restart unity

still tendon
#

doesnt work

hollow crown
#

(it will not fix your errors, but it will help you from making any in the future)

faint iron
mild kelp
#
Hi!
I have a problem in unity that I have been struggling for days. I am making a top down shooter game. For some reason, in some cases, bullets go in the right direction, but in other, they just don't. It doesn't make any seance. Here is the code:
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
bullet.GetComponent<Rigidbody2D>().AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
GameObject bul = Instantiate(bullet_prefab, firePoint.position, firePoint.rotation);
bul.GetComponent<Rigidbody2D>().AddForce(firePoint.up * 5, ForceMode2D.Impulse);
I attached a video showing this. The circle bullets are shot by the second code, and the triangle bullets are shot by the first code. The orange squares in the scene view are the fire points, so I know they are in the right rotation. 

Does anybody know why this is happening?
hollow crown
#

you're not debugging the rotation though, you're debugging the position

#

you can use Debug.DrawRay to debug a direction

#

put firePoint.up as the direction parameter and see where it's pointing

mild kelp
hollow crown
#

They shoot once on the very first frame, so honestly, can't say much

#

debug the direction when it shoots and pass in the time parameter so it persists a bit

#

then you can see what that direction was instead of assuming

abstract grail
#

hey! i have some code, but it doesnt work, basically this code is meant to reload the scene when the player collides with an object, the code is bellow.

void OnTriggerEnter(Collider other)
{
    if(other.GetComponent<Collider>().tag == "Player")
    {
        SceneManager.LoadScene("SampleScene");
        }
    }
paper canopy
#

Could I ask for help here? Unity 2D 2019, c#, I want to write a script to change the order in layer if a sprite name is "Pellet"

turbid heart
paper canopy
#

gameObject.GetComponent<SpriteRenderer>().sortingOrder = 1;

#

this is my unworking script

#

I now the steps, I just dunno what's wrong with the code

#

brb

turbid heart
#

Have you checked if the code runs by Debug.Logging? @paper canopy

#

keep in mind gameObject refers to the GameObject that the script is on

meager mural
#

if you have more than 1 pellet, you need a for loop

paper canopy
turbid heart
still tendon
#

so im working on a platformer game and when my player dies i made it so a clone is spawned but the clone of it , but the script of the clone wont copy correctly

#

this is what the player script looks like in the inspector

#

and here is what the clones script looks like in the inspector

#

it wont take in a respawn point , the health text or the prefab its suposed to clone if it dies again

#

so it wont take in other gameobjects from what i can see , does anybody know what the problem is and how i could try to fix it ?

paper canopy
#

okay, call me a noob

#

I didn't notice the searchbox in the Hierarchy window

#

found all the Pellets, ctrl+A, changed the order

#

I wish I'd found it like 2 hours ago

still tendon
#

Ok so scrap most of what i said above , now i realise that i was askibg to much at once and i didnt make myself to clear

#

So i want to make a copy of my character using prefabs , but when i make the copy of it the text game object wont asign to it , how could i do that ?

odd glade
#

have the active character have a unique tag, and when it dies remove the tag.

#

so then the text can have code to only go to the gameobject with that unique tag.

#

or you could have it look through all the gameObjects for the first one with the script that moves the player, then remove that script when the player dies.

#

Just my idea.

clear furnace
#

why does this happen?

#
            int maxHeight = height + 3;
            height = Random.Range(minHeight, maxHeight);```
#
    {
        for (int x = 0; x < width; x++)
        {
            int minHeight = height - 1;
            int maxHeight = height + 3;
            height = Random.Range(minHeight, maxHeight);
            int minStoneHeight = height - 5;
            int maxStoneHeight = height - 3;
            int stoneHeight = Random.Range(minStoneHeight, maxStoneHeight);

            for (int y = 0; y < height; y++)
            {
                if (y < stoneHeight)
                {
                    SpawnObject(stone, x, y);  
                }
                else
                {
                    SpawnObject(dirt, x, y);   
                }
                yield return new WaitForSeconds(0.1f);
            }
            SpawnObject(grass, x, height);
            yield return new WaitForSeconds(0.1f);
        }
    }``` full script:
snow willow
clear furnace
#

a terrain

#

generator

snow willow
#

yes but

#

you said "why does this happen"

#

what is happening that you don't want to happen

clear furnace
#

the mountain thing

#

why does it go very upo

#

or very down

snow willow
#
            int minHeight = height - 1;
            int maxHeight = height + 3;
            height = Random.Range(minHeight, maxHeight);```
#

this is going to tend to go up over time

#

if you change height + 3 to height + 2 what happens

clear furnace
#

it goes down

snow willow
#
            int minStoneHeight = height - 5;
            int maxStoneHeight = height - 3;
            int stoneHeight = Random.Range(minStoneHeight, maxStoneHeight);```
#

that's then because of this

#

I think

#

Β―_(ツ)_/Β―

clear furnace
#

no

#

the stone does nothing

#

it doesnt edit the height

snow willow
#

wait

#

is height and int or a float?

clear furnace
#

int.

snow willow
#

I would expect using -1 and +2 would work then

#

since Random.range(-1, 2) should give you -1, 0 or 1

#

uniformly

#

what if you do:

height = height + Random.Range(-1, 2);```
clear furnace
#

ok

#

doesn't work still

#

it goes down

snow willow
clear furnace
#

yes

snow willow
#

Sometimes it goes up, sometimes down

clear furnace
#

no

#

not like that

#

it always goes down if the add is 2

#

it always go up if the add is 3.

snow willow
clear furnace
stoic moon
#

I'm currently using this code: Vector3 mousPos = Input.mousePosition; mousPos = Camera.main.ScreenToWorldPoint(mousPos); Vector2 direction = new Vector2(mousPos.x - transform.position.x, mousPos.y - transform.position.y); transform.right = direction; for rotating an object towards the mouse. How would I make it so that instead of doing it instantly, it rotates slowly towards the mouse? I'm assuming it has something to do with rotatetowards, but most of the google searches i found used raycasts and I'd rather not do that if possible.

still tendon
#

how do i get an object to rotate to face the left of my screen?

teal gazelle
#

Im trying to get my 2D circle collider to be able to move over this much of a lip but I haven't had much luck.

I saw a suggestion online to give both of them a frictionless physics material but the player wasnt able to move around a lip this big even with that

#

Is there known ways to fix the physics collisions in this kind of situation so that the player doesnt get stuck on small bumps?

sly brook
#

does anyone have a platformer movment script i could use ? in c#

hot fog
#

hi ik this isnt code based as such but how would i add a z input to unity

snow willow
#

what's a z input

hot fog
#

as in if(input.getkeydown(z) sort of thing

#

because unity doesnt have z with the default settings

snow willow
#

looks like you know how already

abstract olive
#

You want to detect when the Z key is pressed? πŸ€”

hot fog
#

yos

abstract olive
#

Input.GetKeyDown (KeyCode.Z)

hot fog
#

that doesnt work

snow willow
#

it does...

hot fog
#

unity doesnt have an input for z

snow willow
#

lol wtf are you going on about

abstract olive
#

Yes it does.

#

It can do input for every key on your keyboard.

hot fog
#

see

snow willow
# hot fog

that's the input manager and it's irrelevant for GetKeyDown

#

GetButtonDown and GetAxis care about that

abstract olive
#

You can always add your own to the Input Manager as well by increasing the array count.

hot fog
#

yeah im goinna quickly watch a yt vid on how to do that

serene talon
#

Hey all. I am trying to implement an InputField UI component in a 2D game that follows a GameObject around as it moves. I tried placing a Canvas as a child of the GameObject but the scaling for UI is all pretty bad. Any advice on how I can make this work?

craggy roost
#

Hey y'all! Quick question, is there a way to have some "distance" between the mouse and the player moving to it? I have the movement down but I want to have some distance between it if that makes any sense

turbid heart
craggy roost
#

With the mouse, but when I move it around, it follows it directly like this

#

But I want to have like an offset of some sort

craggy roost
#

oh

#

uno momento

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

public class playerMovement : MonoBehaviour
{
    public float movementSpeed = 5.0f;
    private Rigidbody2D rb;
    public Camera cam;
    Vector2 mousePosition;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    
    void FixedUpdate()
    {
        mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);

        Vector2 lookDirection = mousePosition - rb.position;
        float lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg - 90;

        rb.rotation = lookAngle;


        transform.position = Vector2.Lerp(transform.position, mousePosition, Time.deltaTime * movementSpeed);


    }
}
craggy roost
turbid heart
#

Oh, i was going to suggest using lerp where the t value maxes out at 0.8 or something, but prae knows better

#

That’s also an incorrect way of using lerp, in case you didn’t know

#

The third parameter is a progress that goes from 0 to 1

snow willow
#

With MoveTowards your "movementSpeed" variable actually means movement speed in units per second

#

which is actually sensible to think about

craggy roost
#

Ok, thanks. I switched over to MoveTowards

#

Gonna try figuring out how to have like an "offset" between the mouse and the object

turbid heart
#

You could try my suggestion with lerp

#

Read the link i sent, and if you understand it, you’d know that if the third parameter of lerp is 1, your player’s position would be at the mouse position. So.. if it’s a bit less than 1, it would be almost at the mouse position @craggy roost

craggy roost
#

i'll read it now

#

Ok thanks @turbid heart i just tried that and it seems to be working. Just gotta get it to move a bit quicker

turbid heart
craggy roost
#

looking for that section now

#

I think i got it

#

Ok got it to work. Thanks for the help guys! @turbid heart @snow willow

teal gazelle
#

https://cdn.discordapp.com/attachments/669975874455732224/879824907792416808/unknown.png
I'm using unity rigidbody physics for the first time, when I add force in the Green direction, when it hits the flat collider, I would expect it to bounce in the blue line direction, but what happens is it bounces in the black line direction, perpendicular to the wall along it's normal vector.

Its a default 2DCircle collider/default rigidbody against a polygon collider wall, is there an obvious reason this is happening that I am overlooking?

#

Damn it looks like the problem is I had Freeze Rotation on