#๐Ÿ–ผ๏ธโ”ƒ2d-tools

1 messages ยท Page 63 of 1

snow willow
#

The problem is in both places ๐Ÿ™‚

#

i.e. there are multiple problems

cloud crypt
#

Somehow I can never seen to get ground checks to work. Maybe it's too much for my peanut brain. I always just do ground checks as if (rigidBodyPlayer.velocity.y == 0) grounded = true;

#

I'm gonna mess around a bit more with the code, if it doesn't work i'll just have to stick with my previous flipping at random intervals code that at least worked as primitive as it was

cloud crypt
#

I seem to have figured it out, thanks for the help. Though I found another problem in doing so. Not sure why or how but my enemies get stuck on supposedly perfectly flat terrain.

warm mango
#

hey guys, I have a question regarding two colliders with triggers overlapping

#

what happens, is when a player interacts with a gameobj that also overlaps with another trigger, both run at the same time. Is there a way to check if player is already activating a trigger?

#

for example this would happen when the colliders overlap

austere seal
#

You could make a script to check which one's closer, and then only display the dialog for that one

warm mango
#

i see, so check distance from player, and prioritize the closer one

#

okay i'll give that a shot, thank you

cloud crypt
#

I know without the code there's not much one can say but both creatures are using (inheriting) the same script yet they are behaving differently. The size difference isn't the problem either as seen by the TestBots on the left. Any possible ideas to look into or not without seeing the code?

snow willow
kind island
#

if you see closely in the pic (i've zoomed out to protect my sprites from copyright), there is a green thingy called the goblin in the middle right. There is a navigation yellow circle called the seeker, but whatever i do, they always keep the same distance, i couldn't make them together at an equal distance

any way to bring the yellow circle in touch with the green thingy
pls help

compact knoll
#

couple things unrelated to your issue:

  1. you should look into using a tilemap for your level instead of manually placing a bunch of copies of the same object everywhere
  2. nobody is going to come and steal your assets from screenshots because it's just not worth the hassle of doing so

as for your issue, could you please provide more information about what you want to happen?

kind island
compact knoll
#

i assume you are using Aron Granberg's A* Pathfinding since there is an A* object in your scene. the basic AI Path script that comes with it will make it use the shortest path to get to its target which is set with the AI Destination Setter. If you want it to stop when it is within a certain distance of the target you can modify the options on AIPath to change the end reached distance and the "when close to destination" behavior.
If you want more in depth behavior than that, you will need to write your own script to handle it

kind island
#

i want that seeker to meet with the green thing

#

but they move away from each other every time i try to drag it to each other

#

nvm i solved the problem

#

thank you

neat hare
#

Hi! How can I parent an object with code to another object?

fleet remnant
#

transform.parent is your current objects parent that you are running your code on

so you get a reference to a different objects transform that u want to parent to the first object and you go

transform.parent = reference

chrome grove
#

When importing a sprite sheet, I'm getting feathering/weird transparency even with Point (no filter) enabled. Any suggestions?

warm mango
#

i usually add

#

compression to none too

chrome grove
# warm mango compression to none too

Tried that but no luck. Turns out my sheet was too long, causing it to be compressed that way. Thanks for the tip Iw as able to figure it out from that.

inland wind
#

I have a question i was hoping you guys could help me with. i am trying to make a lazer beam enemy. i already have it so it aims at the player but now I want to make it so that if it doesn't hit the playe it doesent just stop at the players currnt position but it keeps going until it hits something.

inland wind
#

idk how tho

#

im relitively new to coding

#

so im not that gud

#

im using a line renderer for the lazer beam with a texture sheet animation.

snow willow
# inland wind im using a line renderer for the lazer beam with a texture sheet animation.

This tutorial goes over a lot. It does prefab projectiles, as well as raycasts with LineRenderer https://www.youtube.com/watch?v=wkKsl1Mfp5M

Let's learn how to shoot enemies!

โ— Get the The Complete C# Masterclass for only $9,99: https://bit.ly/2xfXE6J

โ— Instagram: https://instagram.com/brackeysteam/

โ— Download the Project: https://github.com/Brackeys/2D-Shooting
โ— Get the 2D Sprites: https://bit.ly/2p6VcvH

โ™ฅ Support Brackeys on Patreon: http://patreon.com/brackeys/

ยทยทยทยทยทยทยทยทยทยทยทยทยท...

โ–ถ Play video
inland wind
#

ok thanks

#

i'll check it out and hopefully it helps

#

gotta sleep now tho

#

watch it tommorrow

thin bear
#

I'm trying to add an animated tile to my tile palette with rules

#

I know how to create an animated tile and I know how to create a rule tile

#

but how do I combine both?

#

found it

#

rule tiles can be made animated very easily

spiral solar
#

Found an interesting thing this AM: Unity's Tilemaps have an undocumented bit in TileFlags. It's not in the enum definition in code but they appear to use bit 4 (i.e., 0x20 or 0001 0000) to signify whether or not animation is running. I noticed this in an inspector for an animated tile - there's an inspector button to turn animation on/off. I can post an image if anyone is interested. Curious to know if anyone else has ever seen this.

still tendon
#

what does unity do when i change a tile in a tilemap through csharp tilemap.SetTile(coord, tile)
i have an array that sets the tiles of my tilemap but i do not know what excactly this line of code changes. does it create a new single tile with its own collider or will it be seemless with my previous compound collider?

spiral solar
#

the tile is an asset in your project folder. When you SetTile, it sets a reference in the Tilemap to that asset and calls StartUp, and GetTileData in the tile. The data returned from GetTileData is copied into the Tilemap internally.

still tendon
#

thx. is there any popular unity game that has used a 2d array to set and change tiles in a tilemap in real time?

spiral solar
#

Don't know, but that's what I'm doing in my project which will undoubtedly be unpopular

old snow
#

does someone know how to move an object in the direction of the mouse? i searched on internet for 1 hour and i found only tutorial to move an object to the position of the mouse. thanks

grand cove
ancient path
#

then normalize it

#

and then you got the direction on where the mouse is according to your gamobject
and to move it you can use different ways

grand coral
#

fyi that ^ would look like (Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position)).normalized

snow willow
#

I'd say the opposite

grand coral
#

oh ok

snow willow
#

you want to put the mouse position into a world position

#

then move the object towards that

grand coral
#

i guess i didn't really understand the question then

#

i thought they wanted to move the object as it appears on the screen towards the mouse on the screen

ancient path
grand coral
#

it converts the mouse position on the screen to where it would appear in world coordinates

ancient path
#

and dont use Camera.main in update

grand coral
#

ok well i wanted to demonstrate with one line

ancient path
snow willow
#

they put WorldToScreenPoint

#

on the object position

ancient path
#

oh yes

#

didnt see that

dull vortex
#

I'm working on a survival game where the user can place objects like chests and other structures. I'm looking to create some kind of effect that shows valid placement locations by highlighting them in green and invalid locations in red. The invalid locations are a mixture of non-pathable tiles on a tilegrid, and other gameobjects such as existing structures/trees/etc. It would also need to dynamically update as the player places or removes objects.

My current idea is to create another tilegrid of red and green tiles that I can just turn on and off as needed. I can loop through the impassible terrain tilegrid to find which tiles cannot be built on, but what would be the best way of accounting for the non-tile gameobjects? Or is there a better way to accomplish all this?

crude dome
#

Im trying to make a movement script learning from a video it works fine and uses AddForce but it seems very unresponsive like my sprite gets dragged and when I try to press the other direction it waits like 2 seconds and holding it/spamming the key increases the speed

crude dome
#

i tried force and impulse

#

both does the same

ancient path
#

or acceleration

crude dome
#

ok

snow willow
crude dome
#

ok

#

it pushes me hella far

#

like respsoniveness i mean like when i try to press d then a

#

it waits likee 3 seconds

snow willow
#

yes

#

this is basic physics

#

objects have momentum

crude dome
#

wont increasing the force amount send me flying even more?

snow willow
#

you have full control

#

add more force when slowing down to slow down faster

#

add less when already going fast to not fly off into the sunset

#

the code does what you tell it to do

crude dome
#

okay, im a beginner

#

so it's kind hard

#

kinda*

finite garden
#

Hey guys; I'm trying to make a top down sniper effect where the player right clicks to zoom out. I'm having a few issues; such as my camera moving way too fast due to the mouse being moved around during the aiming process; I tried to remedy this by slowing the rotation of the player but unfortunately I'm having issues making the turning slower.

#

I basically want to create a limited pan camera above a top down player; that can only go out as far as the specified zoom level; while maintaining a constant viewspeed.

old snow
#

@grand cove @ancient path thank you very much! Iโ€™ll see that later

still tendon
#

Right now i'm using a raycast to detect conveyers under a item for my game (The point of the game is being a physics based factory game) to apply a force to the obejct, and it also checks which conveyer under it is on top. Is there any way to optimize this code?

    void ApplyConveyerForceAtPosition(Vector2 position)
    {
        RaycastHit2D[] hits = Physics2D.RaycastAll(position, Vector2.zero, 0, LayerMask.GetMask("Conveyer"));

        int mLayer = -1;
        Conveyer c = null;

        foreach(RaycastHit2D hit in hits)
        {
            Conveyer c2 = hit.collider.GetComponent<Conveyer>();
            if (!(hit.collider is null) && c2)
            {
                int order = hit.collider.gameObject.GetComponent<SpriteRenderer>().sortingOrder;
                if (order > mLayer)
                {
                    mLayer = order;
                    c = c2;
                }
            }
        }

        if (c != null)
        {
            rb.AddForceAtPosition(c.transform.up * c.speed, position);
        }
    }
still tendon
#

I just feel like there has to be a better solution them manually checking sorting order

civic knot
prisma ocean
#

Guys, say I wanted to make an interactable map in a space exploration game like the one in starbound. Could you set me on the right track on how to handle this please? Should I make everything on a ui canvas, or should it be made out of gameobjects (the stars and planets etc)?

#

I saw something about using another camera to view objects on another plane and then render that in a window, would that be a good solution?

short goblet
#

i am struggling with a super weird issue where my FOV shows up fine in the editor but the mesh isnt visible in game

#

has anyone experienced that before? i can share my code but i am not sure if its a code issue or if there is something i need to do in the editor

#

(orange dot is the issue)

still tendon
civic knot
#

If the start position is within the collider?

still tendon
civic knot
still tendon
#

Becuase this function is called for 4 points that might not necessarily have a collider there. 4 points on each item raycast down to see what is beneath them them apply the force at that position

#

Having 4 colliders, one for each point seems even worse then the raycasting

civic knot
#

Are these points on different parts of the item?

still tendon
#

Yes,

#

Just using more effecient checks and sorting would help, since this function is called very often

civic knot
#

Why do you need these 4 points? can't you apply force at the first contact point?

still tendon
#

It lets conveyers rotate items if only part of it is touching it

#

Giving the illusion of more realistic physics then there are

civic knot
#

a properly configured rigidbody would rotate as well.

still tendon
#

Not in the cases I would want it to

#

Let me draw something

#

I'd expect the item between the 2 conveyors to spin here

civic knot
#

hmm

still tendon
#

The proper effect can be achieved in 3d physics with very simple code

#

But not 2d

civic knot
#

Well, if it's performance that you're worried about, I think 4 circle colliders would do better than your raycasts. Assuming you detect collisions from the conveyor belt and not each item.

still tendon
#

Each item does checks,

#

Hm that's a good point though

#

Having the conveyors check would mean a lot less calls

#

I'll give the circle colliders a try,

#

Thanks!

#

Wait but that leaves the problem of only wanting the topmost conveyer to affect it?

civic knot
#

Make sure you cache stuff and don't use too much GetComponent in collision events.

still tendon
#

Right,

#

I'll make sure to

#

Thanks

civic knot
still tendon
civic knot
#

Hmm

#

Well, you could disable those that are below.

#

or can they move something?

still tendon
#

So disabling the entire conveyor would be problematic

civic knot
#

hmm

#

Maybe lock an item to a conveyor belt when it's placed on it so that other conveyors ignore it?

#

Or better: place the item on a layer corresponding to the conveyer and let conveyors on other layers ignore it.

still tendon
#

But other points still obey the conveyor they're over

#

Maybe just ditching the behavior overall would be easier

#

But I'm worried it will look odd

#

For now I'll just experiment

#

Thanks for the help

civic knot
#

๐Ÿ‘

still tendon
#

i need help with save and load game

#

i will use binnary code

#

or Json

still tendon
shy blaze
#

Hey how can i make difference between two objects for example like in game "Where's My Water?"

still tendon
#

ok

next jetty
#

Is it normal that Edge collider 2D object with rigidbody... goes through other objects (terrain), even goes through crazy big chunk of terrain, completely ingoring rigidbodies and colliders?

#

ah it's probably because im moving object with transform

balmy umbra
#

hi im sure everyone knows the "getting stuck while walking" glitch to which the solution is using a capsule collider. But i have to use a box collider so are there other methods to fix it?

next jetty
#

you mean character gets stuck on terrain sometimes? currently investigating stuck problems as well ๐Ÿ˜„

#

Im newbie so cant give an anwser. But i used Platform Effector 2D for terrain and it fixed similar problem for me.

grand coral
#

also try disabling rotation on relevant axes on your rigidbody

balmy umbra
grand coral
#

oh i see

balmy umbra
#

do you know any methods to fix it?

grand coral
#

not sure, i haven't used tilemap colliders before

balmy umbra
#

oh

#

ok thanks for helping me

covert whale
#

the character is getting stuck between each tile's collider, a composite makes them all one collider

balmy umbra
#

i didnt do that, thanks!

balmy umbra
covert whale
balmy umbra
#

i set the velocity

covert whale
#

does it not move at all?

balmy umbra
#

yes

covert whale
covert whale
#

make a new physics material, set it to no friction and put it on one of the rigidbodies the colliders

balmy umbra
#

the collider object got two colliders and one ridgedbody do all of them need the material?

snow willow
#

only colliders can use materials

covert whale
#

try putting it on both

balmy umbra
covert whale
#

how much velocity are you setting the rigidbody to

#

does addForce work

balmy umbra
#

i can still see the collision shape of the tilemap collider is that bad?

covert whale
#

of the individual tiles?

#

it should be one collider

balmy umbra
balmy umbra
covert whale
balmy umbra
#

i have

covert whale
#

could you show a screenshot?

balmy umbra
covert whale
# balmy umbra

sorry i forgot to say you need to check 'used by composite' on the tilemap

balmy umbra
#

ohhh

#

thanks!

prisma ocean
#

Not sure where to ask this; This is a 2D viewport (the black background) on which there is a ui screen, on top of which there is the viewport for another 2D orthographic camera (the red background). The frame and the button are part of the UI canvas. I was wondering how I would make the button appear above the red viewport?

calm wyvern
# prisma ocean

either you need another canvas over the 2D overlay camera or you could render the 2D overlay camera into a texture and use that on a RawImage Conponent in your UI

hollow wolf
#

I have a problem with raycasting: I'm trying to make a ray that check for ground to see if you can jump, but it's randomly letting me jump infinitely above and below certain y levels. Does anyone know if this raycasting code is written wrong?

ancient path
hollow crown
#

float distance = Mathf.Infinity

#

If you don't provide it, that's the default

hollow wolf
#

I saw the documentation about the max distance, but how does that affect the 0.1 distance I'm checking for?

ancient path
hollow crown
#

You should debug what it's hitting regardless

#

Draw a ray there, see if it's not just hitting your character

brittle hollow
#

Looking for a bit of insight on where to begin with making a 2d book in Unity whose pages can be flipped left and right

#

im seeing a few assets on the store like page curl pro

#

but I wanted to get some ideas from the community if theres a better route to go

#

anyone know any good roads to look down?

#

googling "making a 2d book unity" usually gives me scholarly books for learning unity

craggy kite
#

I would just use maxDistance and not hack my way around it to get the same result

covert whale
#

if they're on different canvases then change their sorting layer/ order in layer

next jetty
#

is there any way to make my character to have ability to jump for 0.2seconds, even tho he went off the edge of terrain and already falling?

covert whale
next jetty
#

Ah thx. That makes sence. Hope i can implement this in my mess of a newbie code... ๐Ÿ˜„

slim cradle
#

Can I ask why the PowerUP part is not functioning

#

basically the game is defend a planet while enemies tries to rush b it and you die if planet health reaches 0

compact knoll
#

which part specifically is not working?

slim cradle
#

The powerup part

#

The last part

#

Its supposed to double the ship's speed temporarily

jolly narwhal
#

you're not changing the speed anywhere

compact knoll
#

โ˜๏ธ you are changing timeCounter, but not the speed at all, just using it in your debug statements

slim cradle
#

So I need to change the last part?

compact knoll
#

yes, you need to actually change the player's speed otherwise the speed will remain the same

slim cradle
#

So I basically have to get private void speed?

#

Then somehow fix it

jolly narwhal
#

If you want to increase the player's speed then you'd change the variable called speed instead of the variable called timeCounter

#

So I'd assume writing speed = 4.0f; (which is double the default of 2) instead of timeCounter = 100.0f; would get you started

slim cradle
#

How about if I want a powerup where I do double the fire rate?

wide lagoon
#

Daily round of asking if anybody knows how the tilemap renderer knows the Z (layer) value of a tile, and how (if) I can read it in a shader

covert whale
#

the z layer isn't taken into account with rendering i don't think

prisma ocean
#

Do sprites only work with the sprite mask or with mask and rect mask 2D aswell?

covert whale
prisma ocean
#

ty

old sail
#

When someone is making a clickable map similar to something like FTL's map. Would you do that with game objects or with UI elements? What's the best practice?

craggy kite
covert whale
#

and more options for scaling too

next jetty
#

Can someone help? My trap shoots arrow. But i want arrow to get destroyer after it hits wall. So i used oncollision2d {Destroy(gameObject)}.
The problem is... my trap needs to have arrow object assigned so it will shoot it. After arrow gets deleted, it can't find object and it stops shooting. How to handle this?

covert whale
next jetty
#

ah... thx will try.

hard talon
#

hi! what would be the best way of implementing a push/pull animation whenever my player object is on the right side of my pushable object and is moving right/left, and vice versa? tried setting up a raycast but that didnt seem to work

covert whale
hard talon
covert whale
#

ah ok

#

so you have a reference to the object, and you know the direction the player is moving in

covert whale
# hard talon yup! the player has a raycast, and if the player walks up to an object that has ...

you can get which side the object is on using something like
(object.transform - player.transform).normalised.x and this will give you either 1 for if the object is on the right of the player or -1 if the object is on the left of the player
then you can check that against the player's velocity.normalised.x and if they match (so object is on the left and player is moving left which would both be -1 for example) then do a pushing animation, and if not then do a pulling animation

#

and i assume you already have some sort of system for flipping the sprite of the character depending on their direction, if not then that's just setting the transform's z rotation to 180 or 0 depending on if they're moving left or right

hard talon
hard talon
mint geyser
#

the closer the dot product is to 1 the more aligned the two vectors are

#

so you can do something like if it is more than or equal to 0.9f

#

a visualization if you're into those sorts of things https://twitter.com/FreyaHolmer/status/1200807790580768768

dot product - visualized โšช

the dot of two normalized vectors, as shown here, can say how similar they are

a โ€ข b = 1, same direction
a โ€ข b = 0, perpendicular
a โ€ข b = -1, opposite directions

you might also be able to see why it's sometimes called scalar projection~ https://t.co/vg8TwNZ8qs

Retweets

704

Likes

2876

โ–ถ Play video
hard talon
#

thanks for the visualization though!

mint geyser
#

np

mint geyser
hard talon
#

nope, didnt work

mint geyser
#

sadge

hardy harbor
#

Hi everyone!

#

I have a 2D project with a specific situation in which I need to use a Z scale set to -1f for sprite renderers to allow my shader to work

#

In general, is there any worry with setting Z scale to -1 for a 2D project? Any particular impact that I should prepare for?

#

Thank you!

amber socket
#

I was wondering how I would test to see if the box collider trigger on my object's child is overlapping.

I figured I could use something like this:

player.GetComponentInChildren<BoxCollider2D>().IsTouching() == true
#

But it didn't work, and I tried some other variations as well

turbid heart
amber socket
#

Because I am using it to check for the ground, it would need to check for the ground, but I'm not sure how to do it in the update loop/method

snow willow
amber socket
#

Oh, thx for the info, I actually already got it working

amber socket
#

I actually have another issue to resolve:

#

I have a jumping script I just made that is working really inconsistently, and it's referencing the same thing from earlier.

//Jumping Code
if ((Input.GetButton("Jump") == true) && (player.GetComponentInChildren<BoxCollider2D>().IsTouchingLayers() == true))
{
  Vector2 movement = new Vector2(0, jumpForce);
  player.GetComponent<Rigidbody2D>().AddForce(movement);
}
#

I got the child object to return true upon touching layers which works for now, but I would need to switch this out for something else later.

I am also getting this error where the jumps on my character are really inconsistent.

#

And yes, this is within the update loop

ancient path
ancient path
#

And for physics FixedUpdate is better

#

And a tip is to save and not use get component in that update

compact knoll
# amber socket I have a jumping script I just made that is working really inconsistently, and i...

there's a few things wrong here:

  1. cache your components rather than calling GetComponent every frame for better performance
  2. You should probably be using ForceMode.Impulse for a jump since ideally you would want all the force applied at once
  3. Because your jump is handled in Update, there are probably several frames where it is applying force before it is no longer grounded, you will probably want to use GetButtonDown so it only calls it on the frame it is first pressed instead of every frame the button is down.
    Alternatively for that last part, you could handle your jump in FixedUpdate like No one suggested, it would be more consistent that way and you could continue using GetButton, you would just need a bool to check when to apply the jump force in FixedUpdate
amber socket
compact knoll
#

it wouldn't have worked very well without using the Impulse anyway

amber socket
#

Also, I'm relatively new, so it may take me a bit to truly optimize it, so for now I'm going to get the child of the object.

#

But thank you for the suggestions

compact knoll
#

just cache the references in Start or Awake or something, then you don't have to call getcomponent, even if it is on a child

#

you already have a reference for "player" just get a reference to the rb2d and collider the same way you're getting the player reference

amber socket
#

So for instance,

GameObject generalizedName = player.GetComponentInChildren<BoxCollider2D>();

So I can reference it more easily

ancient path
#

But instead of gameObject do BoxCollider2D

#

Because you are getting that component

compact knoll
amber socket
#

I'll make sure not to screw it up, lol.

covert whale
#

currently you're also comparing the y which isn't relevant and also since vectors are stored as floats using == can have issues since there can be floating point errors

#

so you'll need to convert the x of each vector to an int

novel pewter
#

TIlemap.Color won't work when access and changed at runtime by script, anyone know why?

storm coral
#

the circles are fine, but the poly collider seems like its being shrunk

hard talon
# covert whale so you'll need to convert the x of each vector to an int

how would i go about doing this? right now as is 'normalized' has a red line under it saying that float doesnt have a definition for normalized. i thought just changing what theyre checking specifically would work

        Vector2 playerVelX = rb.velocity.x.normalized;
        if (playerDirX == playerVelX)
        {
            anim.SetBool("isPushing", true);
            anim.SetBool("isPulling", false);
        }
        else
        {
            anim.SetBool("isPulling", true);
            anim.SetBool("isPushing", false);
        }```
marble badger
#

should i check for ground only when in air or all the time

covert whale
#

you may have to cast it to (int) i forgot if you need to

covert whale
marble badger
#

the if is in the update

covert whale
marble badger
#

i don't how i missed that ๐Ÿ‘€

#

are you aware of state design pattern

covert whale
#

yeah i've used it a few times

marble badger
#

should i check for ground in every concrete state
or
check for ground in the update of the context class

#

since one need to know all the time if it is grounded or not

covert whale
#

then you can have your following states inherit from either grounded or air, and so they won't have to run their own ground checks

marble badger
#

i was referring to doing this, inside the context class as in the statemachine class:
update()
{
do groundcheck
currentState.update();
}

covert whale
#

right you could also do it there too

#

then check in each state if it's grounded

marble badger
#

after building my state machine can i pick your brain about it some other time?

covert whale
#

sure thing

marble badger
#

i will ping you then

covert whale
# marble badger i will ping you then

if you need a tutorial for a state machine for a platformer then this series is nice
https://www.youtube.com/watch?v=78PLsHnRXiE&t=325s

Discord Server:
https://discord.gg/uHQrf7K

Git Hub Repo for this project:
https://github.com/Bardent/Platformer-Tutorial

If you wish to support me more:
https://www.patreon.com/Bardent

We are moving on the using a FSM for the player controller now. To get started we need to take a look at the new input system! It's amazing!

โ–ถ Play video
marble badger
#

Thanks. I am also currently checking that out

hard talon
jolly narwhal
#

correct

#

which is why you should type what @covert whale suggested instead

covert whale
hard talon
#

apologies for all of the questions i'm new to unity ๐Ÿ˜…

covert whale
jolly narwhal
#

Do you really want it to be int? If you make it an int then it rounds the value down to the nearest full integer.

covert whale
#

it's already normalized so it would be -1 or 1

jolly narwhal
#

yeah you probably don't want it to be an int

#

unless you specifically want either -1, 0 or 1

covert whale
#

because all that needs to be compared is if it's on the left or right

jolly narwhal
#

carry on then ๐Ÿ˜„

hard talon
# covert whale oh so you need to cast it and that would be ``int playerVelocityX = (int) rb.vel...

ok! that worked ๐Ÿ˜„ possibly last question, there's a red line under playerVelX where I'm comparing it to playerDirX saying "cannot convert int to vector2". how would i solve that? tried doing the same int casting thing on playerDirX but that just gave me a bunch of red lines.

        int playerVelX = (int) rb.velocity.normalized.x;

        if (playerDirX = playerVelX)
        {
            anim.SetBool("isPushing", true);
            anim.SetBool("isPulling", false);
        }
        else
        {
            anim.SetBool("isPulling", true);
            anim.SetBool("isPushing", false);
        }```
covert whale
#

i recommend doing some tutorials on the c# basics it'll help in the long run

hard talon
# covert whale i recommend doing some tutorials on the c# basics it'll help in the long run

will do! last thing, the 'position' in box.position is now underlined in red, says 'GameObject' does not contain a definition for position. why would that be? i have box as a public gameobject that i assigned in the inspector

        int playerVelX = (int) rb.velocity.normalized.x;

        if (playerDirX == playerVelX)
        {
            anim.SetBool("isPushing", true);
            anim.SetBool("isPulling", false);
        }
        else
        {
            anim.SetBool("isPulling", true);
            anim.SetBool("isPushing", false);
        }```
covert whale
hard talon
glossy marten
#

Anyone know how to fix this? My character gets taller and smaller after each animation

grand coral
#

i.e. don't move the helmet part up so far or something like that

#

or move everything down a bit instead of spreading each part out vertically so that the feet stay in the same spot but the rest moves

glossy marten
#

So you mean I shouldn't do this?

#

and have them on the same place?

grand coral
#

i can't see an animation from a series of images like that sorry

#

but if you set the pivot point of the images to the bottom center instead of center center it should help maybe

#

try that before redesigning your animation

glossy marten
#

I tried that but nothing happened

grand coral
#

did you apply the changes?

#

after switching the pivot

glossy marten
#

I will dubblecheck

#

Yes It didn't work

grand coral
#

hmm

#

make sure your images fill the area, it looks like there's whitespace around the images that could be affecting it

glossy marten
#

I sliced them automatic

#

so they all fill the area

grand coral
#

ah that's the problem

#

see how they're all different sizes

#

the green boxes are smaller in the middle

#

try making them all the same size

glossy marten
#

The green boxes only?

grand coral
#

yeah

#

so the middle green boxes will have whitespace at the top

#

which is fine, it won't display

#

but that will ensure that when the image switches, the sprite stays in place

#

even though the image will appear to shrink the object won't

glossy marten
#

I tried making them the same size before but it didn't work but i'll try again

#

It worked ๐Ÿ™‚ thanks @grand coral

grand coral
#

awesome! ๐Ÿ‘

glossy marten
#

Just a quick question

#

The green boxes

#

is the the collider

#

of the animation

grand coral
#

i don't think so

glossy marten
#

whats that?

grand coral
#

the collider is defined separately, along with the sprite object in the hierarchy not with the image asset

#

that green box is for 9-slicing, a method of resizing sprites

#

so to change the size of the sprite image, use the blue circles not the green squares

#

if you move the green squares it only affects something when your resizing mode is set to sliced

glossy marten
#

Is there any way to make seperate colliders for an animation? because I have an animation when my character is very big and I want the collider to be big there aswell but then small when making another animation

grand coral
#

yeah, you can change the size of the collider in a script

glossy marten
#

Okay thanks ๐Ÿ™‚

#

Can I add you?

grand coral
#

sure

glossy marten
#

Thanks, I added you

brittle smelt
#

how do i lock the movetowards function in only one axis?

hoary ginkgo
#

Is there a way to call a coroutine only on the first collision

turbid heart
hoary ginkgo
#

Well let me share my code

#

I have falling bombs that fall and land on platforms, after three seconds they blow the platform up, if it is touching it player it kills the players and the game is over

#

The bombs also destroy each other

#

The issue is if a bomb falls on a platform, then a bomb lands on it, the bombs blow up but the platform/player do not

turbid heart
#

it sounds like what you can do is just use a boolean that is set to true when the bomb touches something, then you can use that to ignore other collisions

hoary ginkgo
#

Sorry, Kind of new here, Posted like that before, no one said anything

turbid heart
#

also, instead of doing this

        if (isTouchingPlayer == false)
        {

        }
        if (isTouchingBlock == false)
        {

        }
        if (isTouchingBomb == false)
        {

        }

you can do

        if (!isTouchingPlayer || !isTouchingBlock || !isTouchingBomb )
        {

        }
#

but of course, it depends on the logic that's going to be in the if statement blocks

hoary ginkgo
#

It doesn't do anything if they are false

hoary ginkgo
hoary ginkgo
#

I am thinking I have to add the collisions to a list or array and then destroy all objects in said array

compact knoll
#

you could do something like

if (other.gameObject.CompareTag("Player") || other.gameObject.CompareTag("Block") )
{
  isTouching = true;
  //do your other stuff here
}

if(other.gameObject.CompareTag("Bomb") && !isTouching)
{
  //do bomb touching stuff here
}
#

then you could call your coroutine only on the first one and if bombs kill each other just have it destroy itself in the second if statement instead of destroying the other bomb, that way you won't have to worry about the state the other bomb is in when that is called

hoary ginkgo
#

Are you saying I should try that under the the OnCollisionEnter2D?

compact knoll
#

Yeah, that would simplify both methods since you wouldn't need a bunch of if statements in both. And you are already passing the collision into the coroutine so you can use Destroy(other.gameObject) instead of using the Find method since you already have a reference to it

#

Oh you're already doing that last bit for all but the player, but you can make that change for the player object too

hoary ginkgo
#

Same Issue

#

Working the same as before though

#

For some reason the last collision is the only object I can destroy

compact knoll
#

You're also calling Destroy on this gameobject first which means the following lines aren't reachable, you need to call that last

hoary ginkgo
#

In the coroutine right?

compact knoll
#

yeah, in the link you sent, just move line 73 down to below the audio manager line, you also don't need to use the isTouching bool in the coroutine

#

just call the coroutine from within the if statements in your on collisionenter and pass the object you want to destroy rather than the collision

hoary ginkgo
#

Still behaving the same.

compact knoll
#

basically you can change it to this

    public void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player") || other.gameObject.CompareTag("Block"))
        {
            isTouching = true;
            StartCoroutine(DestroyObject(other.gameObject));
        }

        if (other.gameObject.CompareTag("Bomb") && !isTouching)
        {
            StartCoroutine(DestroyObject(gameObject));
        }
    }
    IEnumerator DestroyObject(GameObject other)
    {
        yield return new WaitForSeconds(delay);
        FindObjectOfType<AudioManager>().Play("Bomb Explosion");
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
hoary ginkgo
#

Well hot damn

#

Thank you so much

compact knoll
#

Cuts down on most of the if statements and should behave the way you want

hoary ginkgo
#

I typically like to try and solve as many issues as I can on my own, Going to analyze that now that it is working and try and learn from it

compact knoll
#

Actually in that second if statement you can probably remove the tag check so it still dies from touching non tagged stuff

hoary ginkgo
#

Only game components are the player, bombs and blocks.

#

I am real close to publishing this project, will be my first one, Everything is functional, Just going through and cleaning up bugs like this.

#

Well, my first project in google play

#

Well, I got excited too soon

#

Got to add the onexit back in

#

Player was being destroyed if they collided

#

even after they were not touching anymore

brittle smelt
#

Is There a way to lock the movetowards function in only one axis?

covert whale
#

set the desired position for the other axis to be the same as transform.position

north wren
#

I made a linerenderer which connects between 2 cubes but i want to make a new line and if it connects between these cubes

So how can i check if it connected between these 2 cubes?

something like this
if(line.SetPosition == pos1.position)

desert cargo
#

Otherwise you can put colliders on either cube and do a Physics.OverlapBox with a small box at the end of each line, testing for which box they intersect with.

north wren
#

hmm ok ty

blazing mica
#

Does anyone know how to confine the edges of 2D Perspective camera? the cinamachine confiner works fine for Orthographic camera but not Perspective.

twin terrace
#

only way I can think of is a bit of math

#

perhaps there's some way to do that though

blazing mica
twin terrace
#

Let me make a quick drawing

twin terrace
#

you can use trigonometric functions to calculate edge positions

#

but there's probably a simplier solution so search for that first

blazing mica
#

this sounds something that i would try to avoid ๐Ÿฅฒ i think i will try to find alternative for my problem

blazing mica
unborn robin
#

has anyone done anything with sprite shape where you set one of the vertecies to follow a moving game object?

twin terrace
novel pewter
#

Good Evening all, I've started adding in controller support for my 2D platformer and am having issues. Using the joystick horizontal to move my player causes him to sldie about the place, is there anything i can do to fix this?

Edit: I'm using the old input manager

solar thicket
#

by default, the input axes only gradually revert back to 0 when there is no input, based on how high the gravity is set

novel pewter
#

yeah they keep moving past were I expect them too. Setting the gravity higher has helped a lot, i'm gonna do some play testing

#

setting it to 300 helps a lot but after that there are no improvements and the player still slides about.

hazy smelt
#

Why does the game think my mouse is at this tile when it's actually pointing at the one to the right?

#

There's some kind of offset? Could it be camera-related?

snow willow
hazy smelt
#

Not sure if it's code-related though, maybe I'll ask in ui

solar thicket
solar thicket
hazy smelt
#

It's in the inspector, my bad

solar thicket
# hazy smelt

hmmm...are you sure the target graphic is correct? maybe that tile's button highlighting is pointing to the other tile (an off by 1 error in the instantiation, maybe?)

#

i don't feel like the built in system would be wrong about which object your cursor is over, but it's also tricky to really know

#

if i were you i'd shoot a ray out instead of having every object be a button

hazy smelt
#

I swear it was working normally before, I don't know what I changed

#

Yeah I'll debug it again

prisma ocean
#

So I made a gameobject with a sprite mask and changed the scale to fit my purposes, but now when I add objects as children to it, they have strange scales. Because they represent generated planets, I need to change their position based on calculated distances. How will this affect that?

#

Or should the sprite just not be scaled like that?

storm coral
#

How would I go about calling a coroutine every time it finishes itself?

craggy compass
#

hi

#

im trying to make a flappy bird copy, basically

#

but unity aren't recognizing random.rangw

#

range*

hoary ginkgo
#

http://pastie.org/p/0aIecWLRnwioTChHMGGvug
So the first link when a bomb blows up it does in fact destroy the blocks, players and other bombs
Which is what I wanted
Only thing is when a bomb blows up another bomb, the second bomb does not play the animation
The second script I sent you, Plays the animation when it blows up a bomb, but it also plays it when a block and player blow up which doesn't make sense
http://pastie.org/p/0aIecWLRnwioTChHMGGvug
Sorry

#

Anyone tell me how to fix this? I have tried referencs comparing tags, can quite get it righ

#

right

hollow crown
craggy compass
hollow crown
#

Yes, and what are you passing Random.Range, and what does it take?

craggy compass
#

i gonna try anything, wait a minute

storm coral
#

it proboably thinks your trying to pass in a string

craggy compass
#

i made some advances, but it still not working

storm coral
#

what errors is it giving now

acoustic verge
wide bloom
#

This the appropriate channel for UIToolkit stuff?

hybrid kernel
tidal grail
grand coral
#

then use OnTriggerEnter2D instead of OnCollisionEnter2D in your scripts

#

that might fix the issue

fleet remnant
grand coral
#

oh shit u right lmao

fleet remnant
#

you can make it so the rigidbody is freeze rotation so the gameobject doesnt rotate

grand coral
#

i forgot about the ball

tidal grail
#

nvm thanks

#

worked now

next jetty
#

Can someone help me? If raycast hit player - player dies. Line renderers renders a line, but unlike raycast, it bugs out and teleports randomly, when i jump over it.

verbal canopy
#

Hi everyone!
I'm making a 2d isometric game and I want to make the enemy chase the player (or target).
The chase part i got, but i can't make the enemy animation to sync with the movement (run walk-left animation when moving to the left, etc)

To walk towards the player, i use this to get the direction:

var direction = (_target.transform.position - transform.position).normalized;

But i needed to convert this to a Vector2.up, Vector2.down, Vector2.left or Vector2.right to be able to change the animation.

Any tips on how to do this? I don't seem to find anything on google, which leads me to believe that I'm doing something very basic in the wrong way.

solar thicket
keen skiff
#

alright so i'm trying to make a tile based on the tilemap when you click, but i've never coded with tilemaps before and have basically no idea what i'm doing. currently i'm having an error that's shown in the image. Does anyone have any way of doing this
(my code) https://hatebin.com/rbubwvbuua

austere seal
#

Can someone help me figure out why I keep getting an UnassignedReferenceException and NullReferenceException?

#

This will take a minute to explain

austere seal
#

No I know exactly what the error is

#

the problem I'm having is that I'm literally setting it equal to something and it's still giving that error

hollow crown
#

You cannot get an UnassignedReferenceException without trying to use a field Unity is serializing that is unassigned

austere seal
verbal canopy
austere seal
hollow crown
#

Going to have to see the errors

austere seal
#

yeah I'm getting to that

#

these are the errors I'm getting

hollow crown
#

Show the inspector of AdvanceDialogue

austere seal
#

Emitter0 and boss are supposed to be referenced via the BossCollision script

hollow crown
#

So Boss has nothing assigned. You attempt to assign something using BossCollision though, but when does that happen in relation to it being evaluated, and are there multiple AdvanceDialogues in the scene?

austere seal
#

There are multiple versions but they never are supposed to exist at the same time if all works correctly

hollow crown
#

Well it doesn't. That's the issue

austere seal
#

It happens in the Start() method of BossCollision, so after it's instantiated

hollow crown
#

At some point you have a AdvanceDialogue that has not had its boss field assigned before Update runs, that's all this is

#

you can add logs to figure out what's going wrong on your own

austere seal
#

how does AdvanceDialogue not have the boss field assigned at that point though

#

It should literally be assigned by BossCollision upon instantiation

hollow crown
#

I have no idea how your scene is set up

#

if there is an AdvanceDialogue without a boss collision this will happen

#

if there is a BossCollision on a disabled GameObject this will happen

austere seal
#

There's nothing else that accesses it, and AdvanceDialogue is only ever created in accordance with BossCollision's start method

hollow crown
#

If there is an exception thrown earlier in BossCollision.Start this will happen

austere seal
#

BossCollision is instantiated right before AdvanceDialogue, and is never disabled

#

the first error in my image is literally BossCollision throwing a NullReferenceException when I call gameObject

#

I cannot fathom how that would happen

hollow crown
#

It's not

#

it's preDialogue.boss = gameObject;

austere seal
#

yes

hollow crown
#

Only one thing on that line can throw an NRE

austere seal
#

Oh I think I figured it out give me a minute

#

Ok I fixed it

#

thank you

#

I was calling GetComponent instead of GetComponentInChild in the Start() method

#

so yeah, it was a problem with how the prefab was set up

austere seal
#

New issue

#

Instancing an object from a prefab and then trying to disable the instanced object later disables the prefab instead

hollow crown
#

Instantiate returns the instance, if it's not disabling the instance you're not using that

austere seal
#

In BossCollision.cs from above, line 65 sets the variable to the instanced object, and then line 87 attempts to disable it

#

So the variable should be the instance

#

it isn't throwing any exceptions or anything either

hollow crown
austere seal
#

uhhhhhhh

#

Let me check again, those line numbers are what VS gave me

#

Oh I changed the script

#

Lines 67 and 89

hollow crown
#

Well, it looks fine as far as I can see, though your logic is very confusing

#

Like... what's going on here:

emitters = new GameObject[emittersPrefabs.Length];
preDialogue.emitter0 = emitters[0];```
austere seal
#

Could you elaborate? is it because I don't comment or am I just coding weirdly

#

ah

hollow crown
#

emitters[0] is just null

austere seal
#

yes I realize, I was working on that while I sent the new code

hollow crown
#

and I'm a little unsure how in general you can get to instantiating anything into the emitters array if you're trying to access a value in it (that wouldn't be assigned yet) on line 66

austere seal
#

I'm accessing emittersPrefabs for the prefab to instantiate a clone of, which is then assigned to emitters

hollow crown
#

Only on the line after that

#

Which means somehow you'd have to manage to get past accessing something that doesn't exist

austere seal
#

ah

#

I revised it a minute ago so another script would access emitters[0], by the time that happens it does exist

#

the emitters are only supposed to exist after my dialogue closes, so my dialogue instantiates the first one right before destroying itself

#

I think I fixed it

#

Yeah, I figured it out, I think I've got these scripts completely finished now but I'll do more debugging later if I find problems

#

thank you again

#

I find it interesting that you can modify a prefab via a runtime script

#

that can lead to some weird problems if left unchecked by the game dev

blazing mica
# hybrid kernel are you sure the cinemachine confiner doesn't work for perspective cameras?

From what I've experiencing so far, no, perspective camera cannot be properly confined by the space I've set in place.
I found this article about this issue but it's years ago, I couldnt manage to find a more updated info about this

https://forum.unity.com/threads/perspective-vcams-with-2d-confiners.508804/

brittle smelt
#

Is there a way to limit speed on a rigidbody?

covert whale
desert cargo
#

(same thing)

covert whale
#

cool didn't know that

dusky wagon
#

I have a rail like the one shown in the picture for my game. Whenever an object on the rail comes from the left then it follows the three points from A to B to C. If it comes from the right direction its the same thing in reverse, so from C to B to A.

#

Now I want to make it so that if an object drops on the rail it snaps to it and starts moving on it. So if it comes from the yellow point and has velocity towards the right it will move from B to C, if it comes from the orange marker with velocity towards the right it will just go to C and the same thing in reverse if it was to have velocity towards the left

dusky wagon
prisma ocean
#

Can I have sprites have an invariable size on an orthographic camera no matter the orthographic size? or would I have to manually scale them

prisma ocean
#

so if I had 2 objects at different distances, it would appear that they only got further away and not smaller

mighty forum
#

how do I create a meter that shows how high the rocket is in my game?

grand coral
#

if you need details lmk

grand coral
dark dagger
#

I am building a game in unity that is a 2d Platformer using tilemaps for the platform and the background. I want to make it when the player goes up or the right or left that you always see the background without having to build the background so big. I know I saw in one tutorial on how to do it by making the background a child of the main camera, but the background was it's own object in the game and not a tilemap. Does anyone know how to do this with a background that is a tilemap?

dusk yacht
#

I'm in the unity timeline
how do I disable movement while the timeline is playing for my player

snow willow
dusky wagon
#

If you make it a child object of the main camera it will always move with the camera if thats what you want

dusk yacht
covert whale
dusk yacht
covert whale
toxic pilot
#

what is the standard way to change the skins of a 2d character and keeping the existing animations (e.g. run, walk will be same for all characters)?

glad wagon
#

hey im implementing a scoring system, Ive got my UI set up with a canvas and ive made an empty "ScoreKeeper" object in my hierarchy. Id like it to have a script attached which contains param: points per pickup, state: current score and on pickup it should increase the score and then the UI manager Update: should read the score from ScoreKeeper and update the scoreText does anyone know the best way i can go about this? its pretty basic just using a Player prefab and Coin prefabs

covert whale
#

this would be instead of having the UI check every Update, which wouldn't be necessary if the UI was updated whenever the score changes

fleet knot
#

Hello Community, I wanna ask a question, how to make camera projection like Dani "Balls?" Games? When you controll the balls the camera moving as trajectory,sorry for so long question and bad gramma๐Ÿ™

still tendon
molten mesa
#

how do i make my aspect ratio, for an android game, the same for every device?

still tendon
formal crater
#

I cant put these sprites into the animator, are they the wrong file type or something?

snow willow
formal crater
hearty lake
#

hi so i wanna make a button that when i click it a menu apears

snow willow
hearty lake
#

i dont know hot to make it activate that shi

snow willow
#

jsut drag in the object you want to activate

#

and set the function to GameObject -> SetActive

#

and check the box so it passes in true

hearty lake
#

but i dont wanna change scene

#

i just wanna make it visible

abstract olive
#

On the Button component, you can add the object you want to turn on in the OnClick events, and set it to active:"

#

That would be the "quickest and easiest" way to do it.

hearty lake
#

and how to make it invisible on start

abstract olive
#

Just turn it off in the hierarchy?

distant sun
#

How Can I create this mask? I try to use Slider component, but it is filled by stretching my child component

#

for example

dark dagger
grand coral
honest python
#

how do I get a 2D ui line in my 3D game?

grave oracle
honest python
#

No just a 2D line in my 3D world

#

Cuz with line renderer it's rotated

#

Not directly facin the camera

covert whale
honest python
#

why a small Y scale?

#

also using a square is a bit awkward for making a line go from point A to point B

covert whale
#

so that the image is squished

#

you could also just increase the width

covert whale
honest python
#

oh alright

mighty forum
#

how do I create a meter that shows the hight of the rocket?

covert whale
mighty forum
#

what is the video called

#

?

covert whale
#

i'm not talking about a specific tutorial there's plenty out there

mighty forum
covert whale
mighty forum
#

how do I I get the rocket height and maxium height?

covert whale
mighty forum
#

if I send the project file will you help?

covert whale
#

send the relevant scripts and screenshots if necessary to explain

mighty forum
#

When launch button is pressed, the rocket is launched

covert whale
#

and this doesn't look 2d to me it would probably belong in one of the other code channels

prisma ocean
#

Ello, so uh I'm using a spritesheet (imported with multiple and sliced correctly) with these planet icons and applying them to sprite renderers, but the white-blue icons seem to have a tiny bit of the red star icons in them?

#

here's the import settings

peak stirrup
#

Do you have to use the pixel perfect camera to make pixels look right or is there another way?

covert whale
# prisma ocean here's the import settings

when you go into the sprite editor, you can choose custom and check that it's not overlapping, if it really isn't overlapping and that sprite really shows then it could be a bug so try re-importing / restarting unity

glacial obsidian
#

I can't get collisions to work

#

Forget my horrible graphics

#

when I start the ball falls because I have a ridgidbody2D on it

#

but it just falls straight through the ground which has a collider

snow willow
#

And is the collider on the ground 2D?

glacial obsidian
#

yes and yes

snow willow
#

show them

#

show the inspectors of the objects

grave fox
#

Help! Why isn't my collider triggering?

snow willow
# grave fox Help! Why isn't my collider triggering?
  • Does at least one of the two objects have a Rigidbody2D?
  • Do both objects have 2D colliders?
  • Is at least one of the colliders a trigger?
  • Have you tired putting a Debug.Log in the function (outside the if statement) to make sure the code is being invoked?
grave fox
snow willow
#

also recommend:

if (collider.CompareTag("Ore"))``` instead of what you have
snow willow
#

it's a minor performance benefit that's all

#

and less typing

#

anyway did you add the log statement?

snow willow
grave fox
#

It's triggering the debug yeah, but why isn't it destroying?

snow willow
#

Obviously the ore is not tagged properly

grave fox
snow willow
#

or is the collider on a child object of that

grave fox
#

Yeah, that's the prefab

snow willow
#

?

#

Didn't answer my question - which GameObject has the collider?

grave fox
snow willow
#

which GameObject is that

grave fox
#

The Ore

#

The pickup

snow willow
# grave fox

The same one as here? Or is it a child of this?

grave fox
#

Same one

snow willow
#

but wait

grave fox
#

Doesn't have any children

snow willow
#

the ORE has the PickupOre script?

#

Because that script seems to think that the object that it is colliding with is the ore

grave fox
#

Ahh does it need to go on the playerObject?

snow willow
#

yeah you have it backwards

#

you will get the player's collider in that function the way it is now

#

you always get the collider you collided with

#

not your own collider

grave fox
#

Man...

#

This all pretty new to me so forgive the amateur mistakes

hearty anvil
#

(Nvm, I found another solution to my problem!)

compact blade
glacial obsidian
compact blade
#

Yes it is

#

Bro if there is an entire ass single player MMO with that kind of art style I play the shit out of it

glacial obsidian
#

bruh

compact blade
#

Just shitty pixel art The whole way that be hilarious

glacial obsidian
#

that's not even pixel art though lol

#

that's 5 seconds in MS paint

prisma ocean
#

I hope they are placeholders lmao

glacial obsidian
grave yarrow
#

How can I spawn these in my game to be collectibles? I'm following inScope Studio RPG tutorial but i would like my items to appear in game and not spawn on key press

covert whale
grave yarrow
#

Haven't made prefabs yet cause I am not sure if that is the correct approach

covert whale
fleet remnant
#

i mean you can follow the tutorial and just spawn them before hand and not on keypress? like what is the method of spawning u want

grave yarrow
grave yarrow
fleet remnant
#

so how is that different to him?

covert whale
#

you can follow the tutorial and see how it's spawned and then give random positions when they're instantiated

fleet remnant
#

u spawn them on keg press and just give them random positions

#

around ur radius

grave yarrow
#

He spawns them directly in the inventory

#

not on the ground

fleet remnant
#

o

#

well how does he spawn them as a prefab

#

later on

covert whale
#

oh so they're not supposed to be game objects just UI elements?

grave yarrow
#

in his tutorial no. but i need them as such

fleet remnant
#

u can make a generic base prefab that has a script that accepts a SO and sets all its values based on that

grave yarrow
#

do you have an example maybe? would need a pick up option as well

covert whale
#

if you want them to be picked up, have a prefab that takes in an SO, give it a collider2D and set it to trigger, then OnTriggerEnter check if it's a player and if so then spawn the SO in the player's inventory like it is in the tutorial

grave yarrow
#

have a prefab that takes in an SO,
Sorry for dumb question, but how do i do that ? ๐Ÿ˜…

covert whale
grave yarrow
#

yes

covert whale
#

then have a public baseClass collectible where baseClass is the name of the class

#

then you can drag in that SO in the inspector

#

and have this script attached to a game object

#

and make that a prefab

fleet remnant
#

ye

grave yarrow
#

I add Trigger on that prefab right?

covert whale
#

yeah a collider with IsTrigger

#

then have something like


void OnTriggerEnter2D(Collision2D other)
{
    if(other.collider.gameObject.CompareTag("Player")
    {
        other.collider.gameObject.GetComponent<PlayerScript>().SpawnInInventory(collectibleType);
    }

}
fleet remnant
#

^or the other way around if u want

grave yarrow
#

so this would be good?

#

And i would have to do this for each of my items?

covert whale
#

yeah, add a collider with Trigger, and make it a prefab

covert whale
#

and i assume you'll also want it to have some sprite, so you can give it a sprite renderer and change the sprite based on the SO

grave yarrow
#

any way to automate changing the SO with the script when I spawn them?

#

because i need to spawn X different items with my random spawner

covert whale
#

spawn the prefab with instantiate, and since collectible is public you can change that to whatever SO

grave yarrow
#

So pick an item to spawn, change SO accordingly and spawn that prefab?

covert whale
grave yarrow
#

so two highlighted lines go after Instantiate?

covert whale
grave yarrow
#

Like this then?

vocal condor
#

How're you declaring ItemPrefab in the script?

#

If it's of type CollectableScript you would not need to call Get Component.

covert whale
#

since you've set what Collectable is and that's what it uses to get the Icon

grave yarrow
vocal condor
#

Why not public CollectableScript?

covert whale
#

it's got more components on it like a collider and sprite renderer

vocal condor
#

You could always fetch those components.

#

Game Object reference should not be used unless you're only using it for it's Game Object functionality.

#

Best to declare as the type most used; less component calls - they're quite expensive if called a lot.

#

You'd have direct access to GameObject by simply using the gameObject property.

#

If needed ๐Ÿคทโ€โ™‚๏ธ

covert whale
#

wouldn't instantiating from a reference of CollectableScript spawn just a game object with that script

vocal condor
#

Nope

#

It's still the same object simply being referenced as it's component type.

#

Which would simply give you access to the component's members in addition to having access to the specific object; prefab.

covert whale
#

oh ok

covert whale
# grave yarrow Like this then?

so yeah in this case it would be better to do public CollectableScript ItemPrefab;

CollectableScript spawned = Instantiate(//etc);
spawned.Collectable = //etc
#

to avoid a GetComponent call

vocal condor
#

Looks like a lot of calls are being made; more than once.

#

it would just be: ```cs
var spawned = //...
spawned.Collectable = ToSpawn;
spawned.Icon = ToSpawn.Icon;

grave yarrow
#

Will try it in a bit, thanks ๐Ÿ‘

#

It's working! ๐Ÿ˜ฎ

#

Thank you guys so much!

#

๐Ÿ˜„

covert whale
#

nice

grave yarrow
#

welp new problem ๐Ÿ™ƒ

#

When I Try to add to inventory Inventory.Instance.AddItem(Collectable);

public void AddItem(Item item) {
        if (item.StackSize > 0) {
            if (PlaceInStack(item)) return;

        }
        PlaceOnEmptySlot(item);
    }
covert whale
grave yarrow
#

Seems like Instance is null

#

Because if I remove that line and print the name of the Collectable it works

covert whale
#

if it's a singleton, you could be forgetting to set Instance = this; or you're doing it after you try to use AddItem

#

if you're setting the instance and trying to use it both in Start, then it can be out of order

grave yarrow
#

If I set Inventory Active in the scene in works, huh

grave yarrow
covert whale
grave yarrow
#

this doesn't work with static , not sure how else to do it

#

if it's not static then Inventory.Instancecannot be done

covert whale
#

non static script, with a static variable called Instance

#

then set instance = this

#

in Awake is generally where people do it

grave yarrow
#
public static Inventory Instance {
        get { 
            return _instance;
        }
    }

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }
#

like this?

still tendon
#

Hey Guys, So I am making a game where the player is a robot whose battery is broken and the player has to keep it charged and I was working on the Charging Mechanic and I used Physics2D.OverLapCircle() for it.
But for some reason, it always stays "true" even when the player/robot is not getting detected by the station (Charging Station)

#

public class ChargingStationScript : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private Transform chargingStationTransform;
    
    [Header("Script References")] 
    [SerializeField] private PlayerBatteryScript _playerBatteryScript;
    
    [Header("Main Variables")]
    [SerializeField] private float chargingSpeedRate;
    [SerializeField] private float chargingRangeRadius;
    [HideInInspector] public static bool isCharging;

    private void Update()
    {
        //Checking if Player is in range of the Charging Station
        isCharging = !Physics2D.OverlapCircle(
                new Vector2(chargingStationTransform.position.x, chargingStationTransform.position.y),
                chargingRangeRadius);

        //Charging Player's Battery if in range of the Charging Station
        if(isCharging)
            _playerBatteryScript.batteryCapacity += chargingSpeedRate * Time.deltaTime;
        
        Debug.Log(isCharging);
    }
}```
#

This is the Script for the Charging Station... Can anyone help me out?

covert whale
#

now you'll need to have the game object this is attached to be active

#

and you should only access it in Start and not in Awake as instance may not be set then

covert whale
#

you can debug this by setting the result to a collider2d and logging the name of it

still tendon
#

Ya, I got it.... I am stupid

#

Thanks Man

still tendon
#

Cuz I want to fine-tune the Range of the "Charging Station"

covert whale
still tendon
#

Ok Thanks Again!

covert whale
#

np

snow willow
#

no easy way really

#

best solution i've come up with is have several reference points inside one of the objects and check if they're all inside the other one

#

it won't be perfect though

#

collision.bounds is not going to be very accurate either

#

assuming collision is a Collider2D, yes

grave yarrow
covert whale
grave yarrow
#

tilemap inspector

#

player insp

covert whale
#

player's is set to IsTrigger

#

i don't think it'll collide

grave yarrow
#

yep that was it. ๐Ÿคฆโ€โ™‚๏ธ

covert whale
#

you'll probably find that your items won't get trigger messages if they're not set to IsTrigger or if they don't have a script with OnTriggerEnter on them

grave yarrow
#

They worked, I checked haha I was scared they wouldn't

covert whale
#

great

grave yarrow
#

Thanks again! ๐Ÿ˜„

willow tiger
#

why is my character in my game falling through the ground?

grand coral
#

or rigidbodies

willow tiger
#

How do I fix that?

grand coral
#

add a collider or a rigidbody component, respectively

willow tiger
#

Ok, i'll try it out.

prisma ocean
#

Anyone know how I would generate an elliptical ring mesh over which I could tile a sprite? For example I want to make an asteroid belt that appears around a star like the line renderer used for the orbit of this planet, but as a tiled texture

snow willow
prisma ocean
#

_>

snow willow
#

Make an unlit material with your texture

#

set the line renderer to draw it tiled

snow willow
# prisma ocean >_>

If you look at this video the line I'm drawing with the blue circles is done with that technique

#

(ignore the rest of the video)

prisma ocean
#

hmm

#

lemme give that a go

#

er

#

kinda makes a solid colour haha

snow willow
#

something's off

#

play with the tiling in the material

prisma ocean
#

Isn't it because there are 64 vertices?

snow willow
#

waht does your texture look like

#

and hwo did you set up the material

prisma ocean
snow willow
prisma ocean
#

the points for the vertices are generated during runtime

snow willow
prisma ocean
#

aight

snow willow
#

try setting it to very small numbers on x and/or y like .05

#

see if you can get it looking decent

#

and then also try setting it to high numbers

#

I don't remember which is correct

#

I seem to remember that when I did the line effect in the video above, I had to dynamically set the tiling for the material to get the shape looking correct based on the current length of the line

#

something like setting the tiling to 1 / lineLength

prisma ocean
#

well

#

I went all the way from 0.01 to 1000

#

no difference

#

just a solid white colour

snow willow
#

๐Ÿค”

prisma ocean
#

lol that's interesting

#

unlit transparent with repeat per segment

#

OH

#

๐Ÿ˜„

#

just needed to change this in the sprite import settings lol

snow willow
#

sorry yeah there's a lot of settings that need to be right ๐Ÿค”

prisma ocean
#

Time to draw an actual sprite now and make an asteroid belt object ๐Ÿ˜ฎ

#

And figure out how to make an elliptical collider lol

glacial sky
#

Hi guys, I'm trying to make spawn zones with PolygonColider2D. I use raycast, which detects the colider, but it detects the colider as if it was as big as camera.
Does anyone know why this is happening? (the script is attached to spawnZone game object)
btw I'm new to Unity, so I might not know some important basic stuff yet

#

idk if the code could help you, but anyway here it is

public class spawn_entity : MonoBehaviour
{
    public GameObject enemyPrefab;
    public PolygonCollider2D coll;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePosVect3 = Input.mousePosition;
            Vector2 mousePos;
            mousePos = Input.mousePosition;
            mousePos = Camera.main.ScreenToWorldPoint(mousePos);
            // Cast a ray straight down.
            RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

            // If it hits a collider
            if (hit.collider.isTrigger && hit.collider.gameObject.name == "spawnZone")
            {
                if (hit.collider.bounds.Contains(mousePosVect3)) Debug.Log("in bounds"); //this "if" result comes out as false
                GameObject a = Instantiate(enemyPrefab) as GameObject;
                a.transform.position = new Vector2(mousePos.x, mousePos.y);
            }
        }
    }
}```
covert whale
#

because your raycast could be hitting those as you don't have a layer mask

glacial sky
#

yes, I have tilemap colider, but it's not overlaping

#

according to Debug.Log function

covert whale
#

so it could be because .bounds on a polygon collider aren't accurate

#

maybe try with a box collider and see if that helps

glacial sky
#

ok, will try

#

nope, it's the same

lusty olive
#
rb.MovePosition(rb.position + movementPosition * dashDistance);

Why does this dash not work?
rb = rigidbody2D
movementPosition are the axis inputs in a vector2
dashDistance is a simple float

lusty olive
snow willow
#

Not Raycast

glacial sky
#

Thank you, will try that

mint oyster
#

a

honest basin
#

Hello. I wanted to ask if you people could help me with some quick 'AI' for unity and I tried to write some code for it, despite having minimal knowledge about it. I'll send it after this message, but I would like to ask how I should make an actual 2d NPC AI that moves around and still tries to avoid objects and not just walk right into some wall for example. Here's the code:

    [SerializeField]
    float speed;
    [SerializeField]
    float range;
    [SerializeField]
    Vector2 maxDistance;
    public Rigidbody2D rb;
    public float p = 1;
    private bool collided;
    private bool A;

    public Vector2 difference;
    public Vector2 diff;
    public Vector2 Adj;
    public Vector2 length;
    public Vector2 threshold = new Vector2(2f, 2f);

    void Start()
    {
        SetNewDestination();
        StartCoroutine(Thing());

    }

    private void FixedUpdate()
    {
        if (A)
        {
            rb.velocity = speed * Time.deltaTime * (maxDistance - Adj * 0b1100100);
        }

        else
        {
            rb.velocity = speed * Time.deltaTime * maxDistance;
        }
    }

    public void OnCollisionEnter2D(UnityEngine.Collision2D collision)
    {
        collided = true;
        StartCoroutine(Ahmed());
    }
#
    {
        if (collision2.gameObject.CompareTag("avoidObj"))
        { 
            A = true;
            difference = collision2.gameObject.transform.position - rb.transform.position;
            length = new Vector2(Mathf.Abs(difference.x), Mathf.Abs(difference.y));
            AwaySee();
        }
    }
    public void OnTriggerExit2D(Collider2D collision2)
    {
        if (collision2.gameObject.CompareTag("avoidObj"))
        {
            A = false;
        }
    }

    void AwaySee()
    {
        if (length.x < threshold.x || length.y < threshold.y)
        {
            Adj = difference;
            diff = threshold - length;
            Adj = Adj * diff;
        }
    }

    IEnumerator Thing()
    {
        for (int i = 0; i < 1000; i++)
        {
            p = Random.Range(1, 3);

            if (p == 1)
            {
                speed = 0b0;
                yield return new WaitForSeconds(Random.Range(0b1, 0b1100100));
                SetNewDestination();
            }

            else if (p == 0b10)
            {
                speed = 0b10;
                yield return new WaitForSeconds(Random.Range(0b1, 0b1011010));
                SetNewDestination();
            }

            speed = 0x2;
            yield return new WaitForSeconds(Random.Range(0.05f, 0b101));
        }
    }```
#
    {
        maxDistance = new Vector2(Random.Range(-0b1100100, 0b1100100), Random.Range(-0b1100100, 0b1100100));
    }

    public IEnumerator Ahmed()
    {
        if (collided)
        {
            speed *= -0b1;
        }
        yield return new WaitForFixedUpdate();
    }
}
sinful portal
#

does any1 know a way of making a smooth sprite transition? sort of like how terraria does it with the biome backgrounds?

compact knoll
sinful portal
#

ohh... i forgot i could do that... thx

dire kraken
#

Hey im having some issues with some code, basically I want it to be so I click a character then he reacts and a score is added, heres the MESS of a script I got lol https://gdl.space/tasavacete.cs

#

its stored in the canvas

#

i think I screwed up hard and am kinda a nooba t it so ye

compact knoll
#

you are checking for input in Start. You need to do that in Update instead

#

actually that whole thing is super not good. you should consider going through the Intro to C# course pinned in #๐Ÿ’ปโ”ƒcode-beginner so you can better understand how classes and variables and stuff work

ancient path
#

real quit here

sudden dagger
#

I'm having trouble adding a knockback effect to my game. I'm using AddForce() and trying to adjust the x position based on which side of the collider is hit. It generally works. I'd say 85-90% of the time it works exactly how I want but the other 10-15% of the time the knockback ends up being a knock-forward for some reason. I'm unsure exactly why but I'm very new to Unity so I'm hoping it's something easy I'm missing. Here's a gist of my class. https://gist.github.com/brandoncordell/ece347156beec387cf4f50bf139dbe58

whole quartz
still tendon
#

Hey i have a problem with my (thats the problem idk where it is) that my 2d box collidor turns of and on every second. I think its a problem with my crouch

still tendon
#

D

#

do we have to talk abt it again?

#

google this: 2D box collidor turns of and on every second.
and see if u get a helpfull solution

#

answer: no!

abstract olive
#

Because of course you won't find it. It turning off and on isn't a general issue. There is no "make sure the turn off and on option isn't selected."

You said yourself you think it's a problem with your crouch, so start debugging that code. Use logs to track what's happening.

#

And start back tracking through your code. See where you tell the collider to turn off and on, and go back a step to what calls that and why.

still tendon
#

But i followed a tutorial so thats not a porblem with any sort of wrong code or checkings

abstract olive
#

100% of the time, people who claim to have followed a tutorial actually didn't. Assuming you're only following the tutorial and not adding anything custom on top.

#

But anyway, there's nothing anyone here can do based off your question without more information. You need to be more specific about your implementation and such.

late viper
still tendon
#

ye

pallid spade
#

So I was making my first 2d game but every time my character falls through the floor but I have all of the colliders on my character, I don't know what to do?

covert whale
pallid spade
#

the player has a ridged body but I think the floor does not

compact knoll
#

only the player would need a rb2d. both do need 2d colliders though

covert whale
pallid spade
#

no

covert whale
#

it'll need a collider

pallid spade
#

so do i give "tilemap" or "Grid" a 2d collider

compact knoll
#

you'll likely want a Tilemap Collider on the tilemap object

covert whale
#

give the same object that has a tilemap component a tilemap collider and a composite collider, and check 'used by composite' on the tilemap collider

pallid spade
#

thank you it works

inner bone
#

yesterday in animation i said that the animation didn't play on entering a scene which i managed to fix yet now the player does not work

echo sierra
#
    {
        if(timeBtwAttack <= 0)
        {
            if (Input.GetKeyDown(KeyCode.LeftArrow))
            {
                Attack();
                timeBtwAttack = startTimeBtwAttack;
            }
            if (Input.GetKeyDown(KeyCode.RightArrow))
            {
                Attack();
                timeBtwAttack = startTimeBtwAttack;
            }
           
            else
            {
                timeBtwAttack -= Time.deltaTime;
            }
        }
#

is there a better way on doing this so i dont need to repeat everything?

snow willow
# echo sierra ``` void Update() { if(timeBtwAttack <= 0) { if...
KeyCode[] keys = new KeyCode[]{ KeyCode.LeftArrow, KeyCode.RightArrow };
bool keyDown = false;
foreach (KeyCode k in keys) keyDown |= Input.GetKeyDown(key);

if (keyDown) {
  Attack();
  timeBtwAttack = startTimeBtwAttack;
}```
Add however many keys you want to that array.
#

Wrote that on my phone so bear with me ๐Ÿคฃ

#

Best to put that array declaration outside the method too.

covert whale
#

and you can check if this is not 0

echo sierra
#

sorry I dont know much in coding

still tendon
#

Hello i am trying to make a top down movement script but i am getting errors?

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    
    public Rigidbody2D rb;

    Vector2 movement;

    // Update is called once per frame
    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * movespeed * Time.fixedDeltaTime):
    }
}

still tendon
#

Assets\scripting\PlayerMovement.cs(18,82): error CS1002: ; expected
and
Assets\scripting\PlayerMovement.cs(18,82): error CS1513: } expected

covert whale
#

those should be underlined in red

still tendon
#

what is ide i am new to all of this