#🖼️┃2d-tools

1 messages · Page 47 of 1

green anchor
#

i hope you understand my english is not so good

viral plank
#

Okay, before assigning him any random position, why not, take it's current position and add x+5/x-5 etc?

#

I thought, you already have defined a random positions all over the map, or do you want them to be generated on a runtime basis?

green anchor
#

actually thats what i dont want . i dont want to generate random positions all over the map. as you said i want him to move x+5 and x-5

viral plank
#

I am sorry, I am not following it here, so where are you stuck at? At what point?

green anchor
#

okay i want my enemy to move x+5 and stop then flip and move x-10 from current position

viral plank
#

Okay. So, pseudo code would go something like this.

//Defining the target Position
Vector2 TargetPosition;

//At the start of the code initialize the TargetPosition(I would recommand inside the start method)
TargetPosition = new Vector2(this.transform.position.x + 5f, this.transform.position.y);

//Now inside update/fixedupdate/lateupdate whatever that you are using, simply check for it's position
if (Vector2.Distance(this.gameObject.transform.position, TargetPosition) > 0.2f)
        {
            has_Reached = false;
        }
        else
        {
            //Stop
            has_Reached = true;
        }
#

where has_Reached would be a local boolean to determine if it's reached or not.

#

Then perform your logic after that depending on to has_Reached == true or has_Reached == false/!has_Reached

green anchor
#

when distance is almost 0.2f has_Reached switches between true and false so fast

viral plank
#

Then try toggling the value a bit

#

since I don't know what exact scenario of your game is, I won't be able to give the pin-point figures.

meager moat
#

https://paste.ofcode.org/SrtBVq5tnhKrN5iCi3LBPj
Anyone wanna try to crack this nut?

  • unity 2d
  • i have function that makes the player dash by setting the velocity of the player to the unit vector pointing towards the mouse. The problem is that this dash does not have a consistent travel distance and im unsure why.
  • i have tried a lot of simple fixes like moving lines around and making it to where you cannot change the player velocity with wasd during the dash time
    Ive also posted an image of the player’s rigidbody and script settings in case anybody wants to try to recreate the problem.
    Much appreciated!
flint hollow
#

Hey guys can someone lend a hand?

flint hollow
#

or something

#

like you can make the dash go a certain amount

meager moat
#

so more like a teleport?

flint hollow
#

kinda yea

#

its just an idea tho

meager moat
#

i thought about that but i was unsure of how to handle things like hitting walls i know i can use raycasting to figure out if you hit a wall early but not sure how to keep momentum if you hit it

flint hollow
#

hmmm

#

i think you should use "AddForce" rather then new vector2

meager moat
#

i was thinking that maybe the getmousebuttonup was bugging because i press it in between a frame and it does the dash for an extra frame?

flint hollow
#

also

#

use fixed update rather then just update

#

since your using physics

meager moat
#

i thought fixed update was janky with input

#

any way to mitigate that?

flint hollow
#

hmm

#

how so is it janky i never experienced that

#

like give an example

knotty barn
#

Some input relies on frame updates for their state

meager moat
#

ive heard about it not recording inputs because it was recorded in between update intervals and whatnot

flint hollow
#

hmm i see

meager moat
#

so interesting

knotty barn
#

Generally the ones that are along the lines of returns true if started holding on this frame

meager moat
#

fixed update DOES make the dash length consistent

#

but

#

it completely breaks any input

#

🤔

flint hollow
#

maybe unity new input system maybe a work around?

knotty barn
#

Getting input values should be fine

flint hollow
#

if you do experience the jankyness

meager moat
#

well its just that when i release the mouse button it doesnt do the dash half the time

#

more than half actually

flint hollow
#

maybe its how your getting the input

#

like instead of getkeydown

#

just put input.getkey

meager moat
#

well im using getMouseButtonUp(0)

flint hollow
#

wait wait

meager moat
#

well that will just execute the command every frame it sees the button being pressed which i dont want

flint hollow
#

ohh i see

knotty barn
#

Yea that input relies on frames for the "Up" state

flint hollow
#

yea

knotty barn
#

You can get the input in Update and consume it in FixedUpdate

flint hollow
#

would looking for a left click work?

knotty barn
#

Save the value in Update and reset it in FixedUpdate

meager moat
#

so like, scan for the values and then set the dashing boolean to true so that the command executes in fixedupdate?

knotty barn
meager moat
#

i was hoping to just move all of this to 2 void functions called dashStart() and dash()

#

but ill see what i can do

flint hollow
#

Good luck bro!

meager moat
#

that sounds really clunky though 🤔

flint hollow
#

i say take a break and just think about it

#

thats what i do

#

and the answer just hits me

meager moat
#

i slept on it, been at this problem about 2 days now

flint hollow
#

oh geez

#

yea just follow what danny said

#

and see if that helps

meager moat
#

im figuring a way to see how to do that

#

okay so like

#

it works

flint hollow
#

yea?

meager moat
#

it looks janky as hell in code but the dash is still responsive and consistent in length now

#

so screw it

#

thanks @knotty barn @flint hollow

flint hollow
#

glad it works!!!!

meager moat
#

hell yeah

flint hollow
#

im just struggling on why my cube suddenly jumps

#

i want it to be smooth

#

😭

#

im practicing a simple platformer

#

type game

meager moat
#

er

#

define suddenly

flint hollow
#

hmmm

#

like

#

when the player clicks w

#

the cube just shoots up into the air

#

then slowly goes back down

meager moat
#

increase the gravity of the rigid body on the player object

flint hollow
#

alright

meager moat
#

try like 3 instead of 1

flint hollow
#

alright

timber bramble
#

im trying to move an object from 1 place to another, but it just instantly teleport ther everytime

turbid heart
# timber bramble

That’s because you’re immediately setting the position of the object

turbid heart
timber bramble
#

@turbid heart thanks

meager moat
#

so im making a camera system for a 2d game that sets the camera position to the point in between the position of the mouse and the player, which this works.
im trying to smooth the movement so it doesnt feel so jerky. ive tried the lerp function and the SmoothDamp function but both result in the player object being jittery whenever i move.
https://paste.ofcode.org/VMsLXYKPGEJKsWJHLrRdGD - heres the script.
any ways to make the player object not jittery?

meager moat
#

er, no

#

ill look at it tho

#

thanks

meager moat
#

it says "Cannot implicitly convert type 'UnityEngine.RigidbodyInterpolation' to 'UnityEngine.RigidbodyInterpolation2D'. "

#

oh wait i read it closer

#

me dumb i think

turbid heart
meager moat
#

its because RigidbodyInterpolation and RigidbodyInterpolation2D are different

#

i think

#

i did that and it removed my error code

turbid heart
#

uh.. you did what? if you're using Rigidbody2D, then just change it to 2D

meager moat
#

yeah

#

i fixed it

turbid heart
#

does it jitter still?

meager moat
#

no

#

its smooth now

turbid heart
#

awesome

meager moat
#

good good!

#

thanks again bruv

turbid heart
#

glad I could help you solve something this time, haha

meager moat
#

i found the issue with the previous problem tho

turbid heart
#

oh, nice, what was it?

meager moat
#

and it had a solution that made me mad

#

i just had to put the function that actually handled the physics into FixedUpdate() instead of Update()

turbid heart
#

eh, what? I can't believe I missed that

meager moat
#

which makes me mad because it looks and feels really janky

turbid heart
#

which function was it?

meager moat
#

so i slapped the dash start and the dash into 2 functions, and whenever update detects the proper input, it runs dash start, which sets a boolean to true which allows fixedupdate to run the actual dash calculations

#

im bad at explaining

#

heres what it looks like tho

vagrant hatch
#

how do I change the opacity of tiles in a tilemap at runtime?

vagrant hatch
#

setcolor doesn't exist

#

on both the tiledata nor the tilemap

turbid heart
# meager moat heres what it looks like tho

oh, so.. because you're setting velocity, that's why it needs to be in FixedUpdate? Okay 😮 I'm not sure because i dont use physics much. Honestly it scares me, haha, but good to know

vagrant hatch
turbid heart
#

can you show me how you're trying to use tilemap's SetColor? Full disclosure, i've never used tilemap stuff in Unity

meager moat
vagrant hatch
#

and that interface doesn't have a SetColor method apparently

turbid heart
vagrant hatch
#

but that still doesn't explain why this doesn't work

meager moat
#

it may be because of some janky timing things probably idk

turbid heart
meager moat
#

so im making a better pointer for my dash function

#

i want it to give the precise position the player object will end up, even getting shorter if it collides with a wall

#

i want to do this by tiling a " - " visual, so the the visual would look like " O - - - - - __ "

#

hard to explain that any better in my brain

#

but is there a way to do this? like adding a visual effect to a physics raycast?

vagrant hatch
still tendon
meager moat
#

so is it improper to use body velocity when trying to make a proper momentum based aerial movement? whenever i try something it just ends up setting my speed very high

snow willow
meager moat
snow willow
#

Add your acceleration forces

#

But also add drag forces

#

Etc

#

What is the acceleration coming from?

#

Your player's Input obviously but in the lore of the game?

#

Is it a jetpack?

#

Basically add the force that whatever the propulsion system would add when it would add it

meager moat
#

legs :^)

snow willow
#

In the air?

meager moat
#

er good point, but for the sake of fluid controls i wanted to just get an aerial movement that was a smooth transition from left to right, think something like how minecraft aerial movement feels

snow willow
#

Creative mode Minecraft?

meager moat
#

i havent gotten anywhere design wise to think about how movement in air would work from any sort of game lore standpoint

snow willow
#

Creative mode Minecraft is essentially just god mode flying. Wouldn't bother with forces for that but you could just add force/velocity and clamp the magnitude afterwards

meager moat
#

all i need to figure out is, when the player object is in the air, they will have partial control over their direction, essentially adding a force in a specific direction until they reach their cap

#

so id need a hard limit on the aerial velocity if im using addforce?

snow willow
#

If you want a hard limit then yes

#

Alternative is to use a drag function that adds force opposite to the current velocity in a realistic way

#

That will lead to a natural soft speed limit

meager moat
#

i see i see

meager moat
#

im trying to do something like this for the ground so i can allow the player object to slide if they hit the ground at a high velocity

#

but im left with a problem of like, when the object goes from stationary to moving, there is a delay

vagrant hatch
still tendon
vagrant hatch
#

hmm, so OverlapCircle doesn't seem to work when I add a layer mask. Any ideas why?

#

wtf?

#

oooh

#

figured out why

#

had to do 1 << deathLayer since deathLayer is the index of layer, not the mask

green anchor
#

how do i declare (my starting position + 5). (i want to move my enemy to + 5 or -5 from his starting position)

viral plank
#

now change the startPosition as per your wish. where startPostion.x is horizontal position and startPosition.Y is vertical

#

so if you want it to move to right, startPosition.x = startPosition.x + 5f this.gameObject.transform.position = (Vector3)startPosition

#

Kindly check for any compiling error, since I am not on unity/VS at the moment. I just wrote that code in a notepad.

still tendon
#

hey there

#

can someone help me?

#

i am trying to create gravity in my game and this error shows up

turbid heart
# still tendon

gravity doesn’t exist in your script. Are you just trying to change the entire physics gravity, or is it meant to be a variable you declare?

still tendon
#

varible

turbid heart
#

Then declare it in the correct scope

#

Where are you declaring gravity right now?

#

Ooops i just realised that was velocity

#

But yeah, where are you declaring velocity?

frozen moat
turbid heart
marsh oar
#

hello, is there any way to make this code jump only when the player is on the ground, maybe a ground check? if you have any answers, please tell me cause im getting desperate

#

also, i tried mathf.clamp, it doesn't work

elder minnow
#

Box/circle casting works too

mossy canyon
#

I've set the pivot point for a sprite in the Sprite Editor. I drag the sprite into my scene, but the the pivot seems to be dead center. What am I doing wrong? (The gameobject also behaves as if the pivot is in the center.. i.e my character goes "behind" a tree as soon as the center reaches)

ebon flare
#

Is there a 2D equivalent to Transform.forward? Any way to get a vector representing the direction the GameObject is facing in world space? Or am I better off just using the eulerAngles.z?

calm wyvern
timber bramble
#

i have a situation where my character/player is slow/delay to respond on jump as i press space bar, is there a way to improve this?

modest marsh
#

collect your input state inside Update, and apply non-instant forces inside FixedUpdate

scenic hatch
#

Hello! I have a question, if I have a character who is burrowing in the ground and I want them to ricochet off of the wall surrounding the sand, How might I go about doing that?

delicate path
#

Is anyone good with maths? I'm trying to create a "StairZone" that gets an angle /_ from a polygoncollider2d[0] and [1] points, then figures out how much Y to add or subtract as the player moves thru it..but thats beyond my maths

#

Or... just a better way to do this lol

#

i wanna be able to slap this on any stairs, setup the collider and have it work for different steepness

sudden knot
#

Im new but for the math part, im pretty sure you can use height of stair / horizontal length of the stair

#

Then u can add/subtract the y postion of the player with that value

#

Oh wait you are trying to figure it out using an angle

delicate path
#

i don't need to use angle i suppose

#

just however

#

basically just what i should add to my y -- however i get there doesn't matter to me

sudden knot
delicate path
#

height divided by horizontal length?

#

i'll try it, thanks

sudden knot
#

Just use (point1.y - point0.y)/(point1.x-point0.x)

delicate path
#

i had to use (point1.y - point0.y)/(point1.x-point0.x) and then divide the total by 5 (why?) but it works! thanks @sudden knot

sudden knot
#

I dont think you need to divide it by 5, maybe its something related to worldspace or local position, im not too sure bout it. But glad to hear that it works

mossy canyon
#

I have an "action bar" with a grid layout group, where I have added 5 2d sprites. When I drag an image into the sprite, it appears tiny. When I start the game, it's not even visible. How can I make the image/sprite stretch to the boundaries given by the grid group?

fleet pasture
#

Hey guys! im looking for a word processor for unity. Is there something out there or should I do it myself from scratch? thank you in advance!
I'm creating a note-taking app in case the reason for my question is needed.

I have started creating my own one using TMP but i feel that there should be something out there maybe.

green anchor
#

do you guys have any idea how can i exit from if statement. i tried to add my position 0.1f but still cant get out of if statement

late viper
plush geyser
#

Hello, I have a problem with my tic tac toe Game. When I press a field, X and O (the pictures) are invisible but it shows that this field has a value. Can someone help me, please? (dm for more information iguess)

green anchor
late viper
#

even if you do that on both if statements?

humble obsidian
#

wdym by exit it

#

is this all in a while loop?

green anchor
#

i did but imagine like this. my transform.position.x = 10 and my startposition.x = 15

#

no

humble obsidian
#

also if you want to handle something like this I suggest handling it differently

green anchor
#

let me tell you what i really want to do

humble obsidian
#

you dont want to check if the position is the same, you want to check if the distance is > 0

green anchor
#

i want to make my enemy move his starting position + 5 to right

humble obsidian
#

so run that code as long as the distance between the 2 positions is > 0.05f or something

green anchor
#

when he went + 5 stop and go - 5 from his starting position to left

humble obsidian
#

so you want it to patrol an area?

green anchor
#

yes

humble obsidian
#

couldve just said that lol

#

and whats the prob

#

its just infinitely going in some direction?

green anchor
#

no. never get out of first if statement

#

never checks else if

#

i cant get out from if statement when my enemy reaches startingposition

#

that statement is always true

late viper
#

you need to rethink the logic a bit

humble obsidian
#

do what i said earlier

#

patrol the area based on the distance from the starting point

#

then when the distance is greater than some number you can flip directions

#

you dont need Vector2.MoveTowards in this case at all if youre just moving left and right

late viper
#

if you want to stick to move towards you can do:

  1. move towards start position + 5
  2. check if position >= start position + 5
  3. move towards start position - 5
  4. check if position <= start position - 5
  5. repeat from step 1
green anchor
#

i think i found the problem. i exit that if but when i start to move left first if becomes true

late viper
#

yes, thats why we're telling you to rework it 🙂

green anchor
#

this works very well! UnityChanOkay

wide remnant
#

Ping me when you answer, i'm going to bed

burnt badge
#

im getting a wierd issue where niether tranform.position, nor localPosition are showing the same numbers as the the ones in the inspector

late viper
burnt badge
#

Or do i just have to do the calculations manually?

late viper
#

it'll just be transform.position

#

oh wait did you mean the anchored position? then its anchoredPosition3D

#

or anchoredPosition (gives you the Vector2)

burnt badge
#

Gotcha, thanks reo

mossy canyon
#

The blue lightning in this image is an animation. My game is currently paused. When the game plays, this animation is invisible. What could be causing that?

burnt badge
late viper
burnt badge
#

ok, well is it possible to access that exposed property through code?

late viper
#

my impression was that anchoredPosition would update it accordingly but I guess that's not true

#

you may have to just calculate it based on the offset/pivot

burnt badge
#

in the start() function ive printed the position, localposition, and anchroed position, and none of them match up with the inspector

#

im just trying to make a ui object go up when you hover your mouse over it, and then back down when its off of it. to do this, i need to save its starting position to go back to once the mouse is off of it. but for some reason unity is making it difficult to access that information

late viper
#

could you just ignore the values in the inspector then? if you just want to move it up you can just use any of the positions and add to the y component

burnt badge
#

well i want it to be a smooth transition so im using lerp. but the inspector is saying its at 250, -150, but since unity thinks its transform.position is at 0,0, its gonna lerp to 0,0. I dont see how i could lerp it up without using its transform.position.y

sudden knot
late viper
#

yeah, if you just offset it using the position you grab in code, it shouldn't matter what the inspector values are because unity will still lerp it by the same amount

burnt badge
sudden knot
#

Yea the logic is correct but you can do it like this. Im new so i might not get the names right. But you can do this

Vector2 targetPos = transform + Vector2.up * [amount you want it to go up by]

burnt badge
#

ok, but the problem is i want it to be a smooth transition using the Vector2.Lerp function
right now im testing it by doing this:
startPosition = transform.position
transform.position = Vector2.Lerp(transform.position, startPosition, raiseSpeed*Time.deltaTime);
as you can see, in this situation im Lerping it from its position, to its position, and thats making it move for some reason.

sudden knot
#

i guess its the worldspace value and the local position value problem, this is just a newbie guess tho

#

Vector2 targetPos = transform.position + Vector2.up * [amount you want it to go up by]
transform.position = Vector2.Lerp(transform.position, targetPos, raiseSpeed*Time.deltaTime);

just use this cursedface

burnt badge
#

it considers its transform.position as a vector3, so i cant add a vector3 and a vector2

sudden knot
#

oh change it to Vector3 then lol

#

there should be a vector3.up

burnt badge
#

ok, implimented that, it does not go up

#

it goes up and to the left

#

waaaay away

still tendon
#

와 한국인 없냐

#

겁나 홀로 있는 기분이야

sudden knot
#

i have no idea why it goes left MatsuriDerp

late viper
#

one reason might be because you're not using lerp quite correctly
https://twitter.com/FreyaHolmer/status/1175925033002254338?s=19

A quick guide to Lerp~✨

Lerp is used to blend between two things!

It has three inputs: ( a, b, t )
a = start value
b = end value
t = how far we should go from start to end, as a percentage

Here it is in action!⚡blending a value, position, color and an angle! https://t.co/LdA69fLI8N

Retweets

437

Likes

2039

burnt badge
#

thats how ive been using lerp this whole time

#

to move an object smoothly between itself and another point

burnt badge
#

because unity thinks its at 3,0, so if the inspector says its at 200,150, its gonna go to the left

sudden knot
#

that shouldnt happen since it is just the offset

late viper
#

yes, the inspector values should not matter

sudden knot
#

the only thing that i think could go wrong is that you typed something else instead of Vector3.up

late viper
#

try doing it using the anchoredPosition instead

burnt badge
#

trying now

late viper
#

also the "proper" way to use lerp

//declare a float t somewhere at the start of the class
Vector3 startPos = transform.position;
Vector3 targetPos = transform.position + [offset]
transform.position = Vector2.Lerp(startPos, targetPos, t);
t += Time.deltaTime;
#

ah fuck I don't remember how to format code lmao

burnt badge
#

uhhh its not letting me send messages

sudden knot
sudden knot
late viper
#

yeah i figured it out, its just not highlighting anything because none of it is native c# stuff

burnt badge
#

oh hey, it unmuted me. ill send my code blocks using pastebin from now on

late viper
#

you should do it in Update() since its not physics

#

also why are you changing the localPosition?

burnt badge
#

oh right, lemme do that real quick

#

and just testing, ive tried it with both position and localposition, both result in going up and to the left

late viper
#

what happens when you use anchoredPosition?

burnt badge
#

still up and to the left, but faster

#

same thing that happens if i use localposition

late viper
burnt badge
#

forgot to change it to fixedUpdate, did that jus tnow

late viper
#

when I said use anchoredPosition, I mean change all instances of transform.position to anchoredPosition

#

otherwise its not going to work

burnt badge
#

i see, implimenting that hnow

late viper
#

im surprised your lerp works btw, you're giving a vector2 lerp vector3s

burnt badge
#

yeah, this is my first project with unity, its real silly how it handles that

#

commands involving vcector2 and vector3 i mean

late viper
#

don't use GetComponent in update, save it to a local variable first

burnt badge
#

gotcha

#

I printed the targetPos, and its set to (0,10). and the position in the inspector seems to be moving towards 0,10

#

ok, so the inspector shows the position to be (400, -150), so i tried setting the targetPos to (400, -100), and it started moving directly up

#

so then, if we could just figure out how to get the position that the inspector is showing, i can just add my raise height to its y component, and set that as the targetPos

#

but, thats the original problem, position, localPosition, nor anchoredPosition give the same position that is shown on the inspector

late viper
#

is your object parented to something?

burnt badge
#

a text object

late viper
#

whats its position?

burnt badge
#

of the text object? 0,-40

late viper
#

gtg for a bit but I'll be back, this is quite the head scratcher

burnt badge
#

sure thing, i appreciate your time man. hopefully i can figure this out in the meantime

#

this is suuuuuuuuper wierd

#

i tried printing the RectTransform.anchoredPosition as it lerped

#

when printing its RectTransform.anchoredPosition from the Start(), it reads 0,0
but, on the first update frame, after lerping once, it goes to 0.4, -0.1
then in the next frame, it shoots to 400, -150,, which is where the ihnspector showed its position originally

#

from then on, its y position goes up like it normally would through lerping

#

i gotta admit, i think this ones on unity. ive been doing more testing, and it seems like its only getting its TRUE RectTransform.anchoredPosition in Update()

#

and heres the two prints that came from it:

#

so i dont know wtf is going on man, this is the wierdest thing ive seen so far using unity

meager moat
#

so im using addforce to make my player object move from left to right, adding force in whatever direction the player is.
this has an unintended side effect of the controls feeling incredibly unresponsive due to the player having to accelerate to speed.
i tried to fix this by setting the velocity to the player's soft capped speed whenever they pressed one of the direction buttons, but for some reason this part is not working at all, any reason why?

 if (grounded())
        {
            if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D))
            {
                body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
            }
            body.AddForce(new Vector2(horizontalInput * (speed), 0));
            if (body.velocity.x > speed)
            {
                Vector3 dragVel = body.velocity;
                dragVel.x = dragVel.x / (groundDrag*2 + 1f); // zero = no drag. Start with a small value like 0.05
                body.velocity = dragVel;
            }
            if (body.velocity.x < -speed) 
            {
                Vector3 dragVel = body.velocity;
                dragVel.x = dragVel.x / (groundDrag*2 + 1f); // zero = no drag. Start with a small value like 0.05
                body.velocity = dragVel;
            }
            dashAir = false;
        }```
late viper
burnt badge
#

i do have it already in play before runtime. having it be in a viewport might be screwing with the position before it fully initializes. other than that tho idk

#

thats just for testing pourposes, ingame, the object will be added proceduraly, so that might fix the error before it becomes a problem

hollow crown
#

the canvas scaler (and/or canvas) probably just hasn't run before that point

#

if you made your script execute late it may work. There are also some callbacks to look into. UGUI is painful to work with

burnt badge
hollow crown
#

as in script execution order

#

it may not help at all in this case though. I've spent many an hour fighting with UGUI

burnt badge
#

How do i make some scripts execute last in order?

hollow crown
#

use it sparingly

burnt badge
#

Noted, thank you for the info.

subtle geyser
#

Trying to implement some basic pathfinding using 2D tilemaps and came across this github example: https://github.com/pixelfac/2D-Astar-Pathfinding-in-Unity

This seems straightforward enough but the way he's trying to access components seems a bit unweildy..

"object_name".GetComponent<Pathfinding2D>()."gridowner_name".GetComponent<Grid2D>().path[0].worldPosition;

seeker.transform.position = seeker.GetComponent<Pathfinding2D>().GridOwner.GetComponent<Grid2D>().path[0].worldPosition;

Could someone suggest a more efficient way of doing this? Been struggling to find a good implementation of something like this and I feel like this will do what I need it to but can't seem to get this working..

Open to other suggestions as I'm looking for just a basic 2d tilemap pathfinding where enemies move one tile at a time towards the player.

GitHub

A 2D implementation of the Astar Pathfinding algorithm using Tilemaps in Unity - pixelfac/2D-Astar-Pathfinding-in-Unity

meager moat
#

so i have this in my update function

    private void Update()
    {
        // gets a 1 or -1 based on if a or d is pressed
        horizontalInput = Input.GetAxis("Horizontal");
        // gets a 1 or -1 based on if w or s is pressed
        verticalInput = Input.GetAxis("Vertical");
    }```
and im not sure why but ``FixedUpdate`` does not see this change when i try to use these values
#

am i missing something

turbid heart
meager moat
#

yeah,

    private void FixedUpdate()
    {
        if (grounded())
        {
            body.AddForce(new Vector2(horizontalInput * (speed), 0));
        }
    }
#

i tried using debug to see what the value of horizontalInput was and it only returned 0

turbid heart
#

oof

#

does it change inside Update?

meager moat
#

yes

#

maybe fixedupdate isnt calling because there are no physics calculations starting yet?

turbid heart
#

if it isnt calling, you wouldnt see it print 0 😮

#

horizontalInput and verticalInput are declared outside of Update, right?

meager moat
#

yes

abstract olive
#

This probably has nothing to do with any of this, and instead the fact your grounded check is just false.

#

Debug log inside that statement to see if it's even true at any point.

turbid heart
meager moat
#

the line of code right after the addforce command

#

something even weirder

#

my jump key works and when im in the air this function does in fact work fine

#
if (!grounded())
        {
            body.AddForce(new Vector2(horizontalInput * (speed), 0));
#

wait ill try to put the debug there too

meager moat
turbid heart
meager moat
#

no

#

so i just replaced body.addforce

#

with body.velocity

#

and it works perfectly fine

turbid heart
#

um.. okay XD your issues always confuse me, haha. glad you got it figured out

meager moat
#

yeah my issues are really weird

#

i havent figured it out yet though

#

body.addforce not working is still. not good

#

bro im giga confused this is weird as heck

#

i think it's a mass thing

meager moat
#

it was

#

now i need to figure out how to properly slow down the player quickly and smoothly

desert lotus
#

I have a script for player movement and one for reverse gravity. Im doing a test and whenever I step on a blue platform (Reverses Gravity), my ground check no longer allows me to jump on the ceiling. It still allows me to go back down to the floor when I step on a blue platform on the ceiling, but I still cant jump even when I am grounded

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

public class ReverseGravity : MonoBehaviour
{
    private bool CanReverse;
    private bool IsReversing;
    private bool OnRoof;
    public LayerMask BlueSwitches;
    public float CheckRadius;
    public Transform BlueSwitchCheck;
    private bool IsOnBlueSwtich;
    private Rigidbody2D rb;
    public float reverseSpeed;
    void Start()
    {

        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        IsOnBlueSwtich = Physics2D.OverlapCircle(BlueSwitchCheck.position, CheckRadius, BlueSwitches);

        if (IsOnBlueSwtich == true)
        {
            rb.gravityScale *= -1*reverseSpeed;
            IsReversing = true;
            Rotate();
        }

      
     
    }

    void Rotate()
    {
        if (OnRoof == false)
        {
            transform.eulerAngles = new Vector3(0, 0, 180f);
        }
        else
        {
            transform.eulerAngles = Vector3.zero;
        }

        PlayerMovement.facingright = !PlayerMovement.facingright;
        OnRoof = !OnRoof;
    }
}
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{   
    [Header("Basic Movement Variables")]
    public float movespeed;
    private Rigidbody2D rb;
    private float direction;
    public static  bool facingright = true;

    [Header("Jumping Variables")]
    public float jumpforce;
    public LayerMask GroundLayer;
    public float CheckRadius;
    public static bool IsGrounded;
    public Transform GroundCheck;
    private bool IsJumping;
    
     

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

    // Update is called once per frame
    void Update()
    { 
        //Basic Movement
        direction = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(direction * movespeed, rb.velocity.y);



        //Jumping
        IsGrounded = Physics2D.OverlapCircle(GroundCheck.position, CheckRadius, GroundLayer);
        if(IsGrounded == true && Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            IsJumping = true;
        }

        //Flip player
        if( direction < 0 && facingright)
        {
            flip();
        }
        else if (direction > 0 && !facingright)
        {
            flip();
        }
    }

    void flip()
    {
        facingright = !facingright;
        transform.Rotate(0f, 180f, 0f);
    }
}
vocal yacht
#

So im following a tutorial but it wont let me place the tile infront of the background can anyone help?

#

the arrow points at where it will let me place but when i hover over a tile on the background the object disapears

vivid mason
#

Is it possible that the tiles are below the background?
Try moving its position

ruby wadi
#

How can i make an enemy to move and when it collides with a wall, it will turn around

desert lotus
# ruby wadi How can i make an enemy to move and when it collides with a wall, it will turn a...

#unityenemymove #unityenemyai #unityenemywalk

In this video I give you a simple script that allows your enemy to walk from one wall to another back and forth changing its direction after collision. So enemy turns around when he touches the wall and starts moving in opposite direction. It is a kind of very simple enemy AI.

My new game Guess The...

▶ Play video
remote moth
#

i get a nullreference error by set a interger

a.GetComponent<Slot>().ID = i;
#
public int ID;
for (int i = 0; i < size; i++)
snow willow
#

so GetComponent is returning null

#

and you're trying to set ID of null to something

remote moth
#

wait

#
GameObject a = Instantiate(Slot) as GameObject;
#

oh right

snow willow
remote moth
#

ik

snow willow
#

There's the Slot component type, and then there's your Slot variable 🙂

remote moth
#

but bevor has it worked

snow willow
#

a doesn't have a Slot component on it. Up to you to figure out why that is ¯_(ツ)_/¯

remote moth
#

i has deleted the prefabs on the right sideline, and then was all prefabs diselected

sand wing
#

How would I go about locking a camera horizontally, but have it follow something vertically?

snow willow
#

and ignore the x

#

Or follow a proxy object that does that

sand wing
#

ah... thats really simple why didnt i think of that. ok, ty!

ruby wadi
#

Never mind I figured it out

teal lily
#
private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "Player")
        {
            Physics2D.IgnoreCollision(GetComponent<Collider2D>(), collision.collider);
            Instantiate(grasseffect, transform.position, Quaternion.identity);
        }
    }

so basically i always want to spawn grasseffect when the player walks into the collider of the grass, the problem is that it only works on the first ever collision but not on the next ones why is that? is it because of the ignorecollision line?

#

i still want the player to be able to be in the grass

sand wing
#

i think it's because it only occurs when you enter the collision, and not on the frames after that initial collision. i had a similar bug where if the player jumped but did not stop colliding (because the jump did not cause the player to go up any) with the floor, then they did not get their jump back.

teal lily
#

so ontriggerenter is the right method for this?

#

ooooohh

ruby wadi
#

I followed this tutorial video and then i dont know how to take damage

ruby wadi
#

Any video that you recommend?

ruby wadi
#

So how to decrease the number of health?

plush geyser
#

Hello, I have a problem with a tic tac toe Game. When I press a field, X and O (the pictures) are invisible but it shows that this field has a value. Can someone help me, please? (dm for more information 🙂 )

thin prism
#

Hey friends, very quick question that I'm struggling with - what's the easiest way to draw a grid of squares of different colors at runtime?

#

I tried using tilemaps and SetTile but that requires a pre-built tile and I would prefer to be able to just generate a square of a certain color

potent phoenix
#

an issue i'm having where the collisions only work in one way, and the walls say they don't have tag "Wall" even though they all do

#

please lmk if anything else is required to help

ruby wadi
#

How to make a simple animation when I press a button?
Basically when I press "K" on my keyboard, my player will make a shoot animation.

turbid heart
subtle geyser
#
    Vector2 DirectionOfTarget(Transform _target)
    {
        Vector2 startPos = transform.position;
        Vector2 targetPos = _target.position;
        Vector2 directionToTarget = Vector2.zero;

        directionToTarget.x = startPos.x == targetPos.x ? 0 : targetPos.x > startPos.x ? 1 : -1;
        directionToTarget.y = startPos.y == targetPos.y ? 0 : targetPos.y > startPos.y ? 1 : -1;

        return directionToTarget;
    }

Trying to move objects along cardinal directions in a 2D grid but my current code is causing some weird behavior...

Two things I'm hoping to achieve:

  1. Prevent diagonal movement (ideally I'd love to be able to toggle to allow either cardinal only or diagonal only but if I can only easily have one it would be cardinal)

  2. If there is an obstacle between the enemy and the player, rather than having the enemy keep trying to move into the obstacle, to pick a new direction at random on it's opposing orientation (i.e. if it moves down and hits an obstacle, randomly choose between left and right)

I realize A* would probably solve the latter issue but that seems overkill for what I'm trying achieve as I really only need basic cardinal movement for objects.

rough yarrow
# subtle geyser ```cs Vector2 DirectionOfTarget(Transform _target) { Vector2 sta...

You are changing both directionToTarget.x and .y at the same time, meaning that sometimes it will actually move diagonally. You'll need to check if you've moved in either direction, and not apply the other direction if you have. This would probably make it biast to moving either horizontal or vertical first, but you could alternate each position update as an example.

timber bramble
#

im trying to make an option move according to set distance, then back

#

but upon running the code

#

it just shake violently when it reached its max range

#

as if code are fighting to move < and >

turbid heart
#

also in the future please use a paste site. see the pinned messages in #💻┃code-beginner on how to post code here

timber bramble
#

eh

#

is there an operator to flip a value from positive to negative

#

or negative to position?

turbid heart
timber bramble
#

thx

leaden sky
#

How do I fix the bullet "jumping" over the wall? The bullet has rigidbody2d and capsule collider. It gets a velocity at the start. Theoreticaly I could do the walls thicker but I want this to work against moving ships as well.

lean estuary
leaden sky
#

cache what is in front and what is behind the bullet? Will that work for the enemiesi as well?

lean estuary
#

cache the previous raycast, it will have a collision location (and previous bullet position)

knotty barn
#

Would continuous collision not be able to deal with this case 🤔

#

Does it ever hit the wall?

lean estuary
#

Long time ago working on breakout type game I think I've had cases it going so fast continuous wasn't working properly too

leaden sky
#

I thought continous would do it. And yes,most of them do hit the wall

leaden sky
lean estuary
#

Once bullet is outside of the game space, you use last raycast point to place the object there instead. And use raycast vector with hit angle to calculate proper ricochet, I think there's a bult in method for that as well

#

(and use resulting ricochet angle to set new velocity direction)

leaden sky
#

yeah so the bullit is suppose to be destroyed on impact. But should work on more than just the walls. Ideally you awnt to hit an enemy 🙂

lean estuary
#

even simpler, just register when it is outside

leaden sky
#

for the walls yes, but not for enemies

lean estuary
#

raycast should be the length of velocity so you can tell if it hit something, in this case hit something next frame when raycast says you are about to hit it

leaden sky
#

what if an enemy moves at the same time. So raycast sees the enemy but the next frame the enemy has move and didn't actually get hit?

lean estuary
#

Default frame is 1/50 of a second

leaden sky
#

so just ignore that very small possibility?

lean estuary
#

If you want more detailed calculation you can easily calculate it with object and bullet speed at that frame as well

leaden sky
#

but with a raycast that looks at the range of the speed, do I even need collission detection/OnTriggerEnter ?

leaden sky
lean estuary
#

You are not caching raycast, bullet will be destroyed just closing in to the wall. You can also use Debug.DrawRay or line to visualize raycasts, travel path. Also you should use velocity as raycast direction.

leaden sky
#

sorry don't understand why I need to cache it. If it is going to hit in this fixedupdateframe (I suppose the move is done later in the frame) then it should die this frame? I dont want it to bypass the wall and get destroyed on the other side of the wall /enemy

lean estuary
#

When you raycast it, it hasn't hit yet. When you hit and go past then you need to use information

#

(previously cached)

leaden sky
#

so if the backwardraycast hits withing velocity range and the frame before the same object was hit with teh forward raycast+

lean estuary
#

if you raycast back you may get another object entirely

leaden sky
#

?

#

but the raycast hit is limited by the velocity so won't it hit this frame?

#

and if I raycast forward next frame, I might have skipped it? and raycast will return empty?

lean estuary
#

velocity is per second so should be cut by 50 to be per frame

#

it will also ensure that you are looking at actual data, if you have gravity or drag affecting it

leaden sky
#

gravity and drag is set to 0

#

and it seem to be able to skip the wall

#

the ray is drawn from the transform.position which shows this

cerulean lily
#

hi, why the code lice StartCourotine or SerializedField doesnt light up in my vs? do i need to install some sort of module or something?

#

and heres the errors

leaden sky
#

its misspelled

#

StartCoroutine

cerulean lily
#

oh ok, but still, it didnt light up even when i started writing start

#

or just corrected me

lean estuary
#

@cerulean lily You need to setup VS to work with Unity. Configuration guide pinned in #💻┃code-beginner

cerulean lily
#

oh sorry

#

ill do that

leaden sky
#

am I doing it wrong or is a drawing problem. My debug draw shown the wrong way (or it's just last frames debug arrow)

#

should point up left

#

the bullet can still go through my wall

lean estuary
#

You need to use Rigidbody position instead

#

Transform is not part of physics

leaden sky
#

ohh I see. and apparently I am colliding with myself as well 🙂

#

I just did only find example of raycast using transform.position

leaden sky
lean estuary
#

Like I said previously, once you overshoot you move it back to collision position yourself using cached raycast hitpoint.

#

It will be almost the same as if physics caught collision correctly

leaden sky
#

and I know if it overshoots when the forward raycast different from the wall?

lean estuary
#

you know it overshot when cashed raycast says there was a collision when it didn't happen

leaden sky
#

OnTriggerEnter2D is after fixedupdate right?

lean estuary
leaden sky
#

so frame 1 I find a raycast collission.
on frame 2. we have now overshot the target and no raycast is detected so we think no detection is made because it will be found later in the execution order

lean estuary
#

At this point you don't need collision even really, just check cashed raycast every frame. Or you can use coroutine to yield until FixedUpdate finishes and check then if collision happened.

leaden sky
#

yeah, my thought exactly. As soon as a cached one existing. Move it back and destroy it.
Thank you very much.

leaden sky
lean estuary
#

It shouldn't be rendered inside the wall, as it should be moved on the same frame right away, then rendered

lean estuary
#

you should be yielding to end of frame

thorn echo
#

is there something i can to reduce the delay between sound play and the object being destroyed?

lean estuary
#

Check that you are moving to the correct point

leaden sky
#

was directed towards me

#

and yes the point is correct

thorn echo
leaden sky
#

I have tried by just disabling fixedupdate as soon as the object dies instead of destroy

lean estuary
#

Print out the positions

leaden sky
lean estuary
#

Use step forward on pause in editor, printing out position to see what's happening

#

Maybe previous hit raycast is too short

#

it should show anomalies step by step

leaden sky
#

I havent used that before

lean estuary
# thorn echo

You are running a loop waiting for the sound to finish playing, you don't need to do that.

lean estuary
leaden sky
thorn echo
lean estuary
#

yes

#

Removing that you don't need it to be a couroutine as well, so replace IEnumerator with void to return nothing

thorn echo
#

ohk

#

Error - audiosource.isplaying can not be used like a method

turbid heart
lean estuary
thorn echo
#

already did that, or should i remove semi colon too

lean estuary
#

all that is contains

thorn echo
#

ohk

#

but if i remove the loop the sounds won't play it destroys as soon as player collides with the object which any sound

leaden sky
#

yeah this has not yet found anything from the raycast.

lean estuary
#

This looks like a correct case

lean estuary
#

Use a sound manager and make it play on event

thorn echo
#

ohk i just found sound manager a little hassle 😅
Thanks for the help

lean estuary
leaden sky
#

@lean estuary I put the raycasting WaitForFixed update and it looks great

#

it was raycasting because having its physics position updated I believe. So the raycast was from previous tick position

rocky temple
#

heya I'm trying to make a collider a trigger from inside a script I've tried a couple of things but they don't seem to be working any tips?

abstract olive
#

Yeah, show your code. 😛

rocky temple
abstract olive
#

It's adding the SpriteRenderer, but not the Collider?

rocky temple
#

it added the collider perfectly fine I just don't know how to make it a trigger

abstract olive
#

Any property you see in the inspector can by changed like how you were doing it with the .sprite

#

In this case, you would use .isTrigger = true;

rocky temple
#

ohh I got it now

#

tyvm 😄

worldly reef
#

I am working on a topdown game right now where the player can recall a projectile and then launch it around the map. I'm running into an issue where at high speed, the projectile gets stuck in walls. I am manually adjusting transform.position because I don't feel like messing with physics and I think it gives the result I want better. I have detections sent to continous and have decreased fixed timestep. That's all helped it happen less, but it's still a problem. I also write a OnColissionStay2D that bumps the projectile out when it gets stuck, but it's does not really fix the problem and doesn't look great. Anyone have any other ideas for fixing this and keeping my existing movement?

remote moth
#

whats the best way to save and load GameObjects and data?

worldly reef
worldly cove
#

I'm having trouble destroying an instantiated game object. When I pause the playback, I can see that the cloned object still exists in the hierarchy tab.

remote moth
worldly reef
# remote moth and whats the best way to save a "chunk" (a object with a lot childs sorted by x...

I'm going to admit that's a bit beyond me, haha, but this should get you moving in the right direction: https://www.youtube.com/watch?v=XOjd_qU2Ido

Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.

● Easy Save: https://bit.ly/2BzgdXb

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

·····················································...

▶ Play video
remote moth
#

can i save the object in script as prefab, and to save override the prefab?

worldly reef
#

Might be worth looking into

remote moth
#

and were can i load it?

#

So i can save, but loading

string localPath = "Assets/saves/chunks/" + save.name + ".prefab";
localPath = AssetDatabase.GenerateUniqueAssetPath(localPath);
PrefabUtility.SaveAsPrefabAssetAndConnect(save, localPath, InteractionMode.UserAction);
worldly reef
#

Can you save in the Resources folder and then use Resources.Load?

remote moth
#

i try LoadPrefabContents

#

when not i use Resources.Load

#

it exist only one problem

#

when it save, the game freeze a half second

#

can i do it in a thread?

vast plume
#

Hi i just made a 2d player controler and now i want to make a cameramovement thing it works but i dont know how i can do it so it stops moving at an certan point
How can i do this?

remote moth
#

why is "LoadChunk" everytime null?

private void SaveChunk(GameObject save){
  string localPath = "Assets/saves/chunks/" + save.name + ".prefab";
  localPath = AssetDatabase.GenerateUniqueAssetPath(localPath);
  PrefabUtility.SaveAsPrefabAssetAndConnect(save, localPath, InteractionMode.UserAction);
}

private GameObject LoadChunk(int num){
  string localPath = "Assets/saves/chunks/chunk " + num +".prefab";
  localPath = AssetDatabase.GenerateUniqueAssetPath(localPath);
  GameObject o = Selection.activeObject as GameObject; 
  if(o == null){
    return null;
  }
  return PrefabUtility.LoadPrefabContents(localPath);
}
snow willow
#

maybe o is null or is not a GameObject

#

maybe LoadPrefabContents is returning null

#

maybe both at different times

remote moth
snow willow
#

If you can succesfully isolate the data you need to save from referencing any of that, you can definitely do your saving in a background thread.

remote moth
#

and where is thenn the best way to save objects without lags

#

as prefarb

#

can i give the thread a paramenter

#
Thread thread = new Thread(
() =>{
  SaveChunk(d);
  Destroy(d);
  }
);
remote moth
remote moth
#

can i anything do becaus the error, or can't i do any with new threads to save the object

deep urchin
#

If I use OnCollisionEnter2D do both objects need to have a collider2D and a Rigidbody2D?

#

Or does just the object with the script need a Rigidbody?

turbid heart
deep urchin
#

ok

remote moth
rocky temple
#

is there a way to find all objects with a certain tag and then set them all to not active?

sudden wasp
#

can someone here join a VC with me and explain the way to use layers in unity i am very confused, all the Youtube videos don't help

#

2d

#

Oh wrong chnneæ

#

channel

#

sry

rocky temple
snow willow
rocky temple
deep urchin
#

I am trying to get an object to face towards the mouse. Yesterday this script was working, but then I saved everything, re-opened it today and I got an error.
The error is NullReferenceException: Object reference not set to an instance of an object Here is the code:

Vector2 direction = (mouseScreenPosition - (Vector2)transform.position).normalized;
transform.up = direction;```What is the problem?
late viper
snow willow
deep urchin
deep urchin
deep urchin
#

Completely different question, does OnCollisionEnter2D require a dynamic body type? Because If I set it to Kinematic it doesn't work, but I want it to be Kinematic so it isn't effected by physics.

snow willow
#

A kinematic rigidbody collider (kinematic RB with a collider) will only cause OnCollisionEnter with dynamic rigidbody colliders (dynamic rigidbody with a collider)

#

It won't collide with static colliders or other kinematic rigidbodies

#

(a static collider is an object that has a collider and no Rigidbody at all)

deep urchin
#

Ok thanks

snow willow
#

The trigger matrix is a bit more forgiving

#

kinematic rigidbodies will cause trigger messages with any trigger collider

deep urchin
#

Doesn't that mean kinematic wont detect collision if it hits another kinematic?

snow willow
#

It will work if one of the two objects has a trigger collider

deep urchin
#

Do you mean this thing?

snow willow
#

that makes the collider intoa trigger collider

#

note that if you want to detect that in code it's a little different:

void OnTriggerEnter2D(Collider2D other) {

}```
deep urchin
#

Just get rid of private at the beginning?

#

Oh wait Its OnTriggerEnter instead of OnCollisionEnter

snow willow
#

yes and a different parameter type

#

Collider2D instead of Collision2D

deep urchin
#

Ok thx

deep urchin
#

Another completely different question, I tried using this script

{
        Destroy(gameObject);
        Destroy(collider);
}```to destroy both this object and the object it collides with, but it doesn't do that, It just destroys the object with the script. Is there anyway to destroy the object I collided into in the same script?
forest hamlet
#

Because you're destroying the gameobject that has the script before the object it's colliding with, thus it never reaches the second destroy call @deep urchin

#

It's like if someone said they were going to shoot themselves, then shoot someone else, they would never get to the second part because they were dead lol

worldly reef
#

On mobile so formatting going to be bad, but I think you want Destroy(collider.gameObject); Destroy(this.gameObject);

forest hamlet
#

oh yeah that too

snow willow
#

It's what Wrimor said

deep urchin
#

Yes, I did what Wirmor said and it works now

snow willow
#

the difference is destroying the whole other GameObject vs just destroying its Collider component

deep urchin
#

Yes

split edge
#

why does my 4k sprite look so bad on Unity?

#

it looks like an upscaled sprite

#

this is the original resolution

#

why would the game make it look like this

#

like I am completely blown away at why would Unity destroy this visually

snow willow
split edge
#

yeah, set to none

#

that was bilinear filtering btw, this is how it looks like in point

#

like

#

how

late viper
split edge
#

mipmaps enabled, sprites arent a power of 2, I dont think i can meet that requirement

split edge
#

Everyday I am more surprised at how shitty Unity is

late viper
#

it doesn't surprise me at this point 😄

split edge
#

like this isnt a crazy requirement

#

I am not even downscaling them

#

Love to wake up to see unity doesnt have a functional sprite renderer

late viper
#

i mean you're effectively downscaling them when you render them at that resolution

snow willow
#

I'm trying to figure out what you're expecting this to look lioke

#

is it the lack of antialiasing that's the issue?

split edge
#

it doesnt look like a 650x200 sprite scaled down, it looks like a 60x20 sprite scaled up

#

I guess this is better but thats trilinear filtering with a 16x anisotropic factor

#

for comparison, this is what a downscaled version should resemble

#

Is not like I am doing something crazy, my viewport target is 4k , these sprites should look as they are

late viper
# split edge Is not like I am doing something crazy, my viewport target is 4k , these sprites...

unity's downscaling algo just isn't as good as gimp, according to the unity forum post https://forum.unity.com/threads/downscaling-sprites-in-unity-vs-image-editing-software.553807/#post-3669721

hearty tiger
#

I'm making a 2d sidescroller (orthographic camera), and have been using Z coordinates for sorting, however this is affecting sprite size and all collisions to an extent

#

How am I meant to sort objects?

turbid heart
hearty tiger
#

ok thanks

#

should the higher numbered layers appear above the lower numbered layers?

#

does layerering depend on z position whatsoever if objects are on different layers?

turbid heart
#

Layering takes precedence over z sorting

turbid heart
hearty tiger
#

it wasnt working so i asked

#

but turns out i was looking at the layer of the gameobject

#

not the sprite renderer

still tendon
#

#Hello Everyone. I don't know what happened on this code line:

anim.SetFloat("speed", Mathf.Abs(movePlayerVector));

#It show the error result like this:

NullReferenceException: Object reference not set to an instance of an object
CharacterMovement.Update () (at Assets/Scripts/CharacterMovement.cs:34)

Help me!

still tendon
thin prism
#

Can somebody help me figure out how the heck I'm supposed to color a tile in a tilemap? There are so many things online for it but nothing is working.
Here's what I'm currently working with:

                Color color;
                // Logic to select a color - will always have a non-white color
                
                Tilemap.SetTileFlags(pos, TileFlags.None);
                Tilemap.SetColor(pos, color);
                Tilemap.RefreshTile(pos);
                // After all this, all tiles are still white (the sprites color)
velvet moon
#

hey guys
I am having trouble in unity 2D with Post processing
I followed a postprocessing tutorial but it wouldn't work
i am using the Light (URP)

sweet nest
#

Is there a way to only get touches that dosen't touch a canvas element?

woeful sentinel
#

You can use RectTransformUtility for that then check for mouse position

sweet nest
woeful sentinel
#

its the same as input position

#

meaning your touch input

sweet nest
#

i just want to know how to make something like this

if (Input.GetTouch(0) is not touching a Ui element)
{

}

#

i found a solution:

worldly reef
#

What's a good practice to get Cinemachine to always keep some object in frame (the player for example) but example to a limit to keep some other object in frame? I correctly have it setup to follow a target group of the player and the square and look at player, but that doesn't do what I want.

#

Do I need to write some code that adjusts the camera if the square gets too far away or that available already in cinemachine?

snow willow
#

you can also play with the weights of thje items in the target group, and maybe create a script that will remove an object from the target group if it goes too far away from the player

worldly reef
#

Found a solution I'm pretty happy with. I setup two virtual cameras. One focuses on the target group and one focuses on the player. When the square gets too far away I transition to the player one. When the square gets closer, I move it back to target group.

snow willow
#

cool

worldly reef
#

Thanks for the help. Wouldn't have gotten there without you!

fickle kiln
#

hi, basic question, but how do I initialise prefabs at runtime? So I have 9 'number tiles' as prefabs and I want to have 7 of them chosen at random displayed at the beginning of a scene on a canvas in certain positions. I think I should probably use a list as they are mutable

I found this which just initialises a prefab and you attach it to a game object. If I have 7 prefabs to initialise, do I need 7 game objects, each with this script?

using UnityEngine;
public class InstantiationExample : MonoBehaviour 
{
    // Reference to the Prefab. Drag a Prefab into this field in the Inspector.
    public GameObject myPrefab;

    // This script will simply instantiate the Prefab when the game starts.
    void Start()
    {
        // Instantiate at position (0, 0, 0) and zero rotation.
        Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }
}```
snow willow
#

so instead of public GameObject myPrefab you would use public GameObject[] prefabsArray;

#

then look up how to do a for loop over an array

fickle kiln
#

ok, how about how to choose 7 random prefabs to add to the array from the 9 I have available?

snow willow
woeful sentinel
#

e.g: prefabsArray[Random.Range(0, prefabsArray.Length)];

#

It would get random index number in your array

snow willow
#

yes you can do that but if you want to pick 7 out of the 9 that code will lead to duplicates if called repeatedly

#

which is why I suggested the shuffle method

woeful sentinel
#

Or just add them to a List and eliminate each index number of the successful instantiated object

snow willow
#

that's much slower though

#

but for 9 elements it's not going to matter either way

woeful sentinel
fickle kiln
#

for context, I'm trying to adapt a real life puzzle board game to unity...this is the 'pool' of number tiles the player can pick from...this was taken from an older python file so excuse the syntax - it's just 5 number 1 tiles, 7 number 2 tiles etc

numberTiles = {1:5, 2:7, 3:8, 4:8, 5:8, 6:7, 7:7, 8:7, 9:6 10:4, 11:3, 12:4,}

so yeh the player can have duplicates as long as there's enough in the pool of available tiles

snow willow
#

I mean think about how you would literally do this in a real life board or card game

#

you would shuffle the pile or the deck

#

and then take the top 7 items

#

I suggest doing the same thing in your code

vast plume
#

Hi, there are some bugs in my 2D game i cant really explain it
can i talk to someone in a call to show it?

turbid heart
turbid heart
fickle kiln
#

I have a problem that I asked last week but never got resolved...I have an orthographic camera that when I change it's size in the editor, doesn't actually change size in game

orchid nest
#

So I came here yesterday with my unity 2d isometric snapping system

#

but I am still having trouble

turbid heart
vast plume
#

So my issue is that i have a 2d platformer game with moving and non movingplatforms and coins that do nothing jet you just can colekt them
when i go on the moving platform and go back to the ground after a while the player starts changing his size

snow willow
#

Two things are happening:

  • Your player is being set as a child of the moving platform when your player jumps on the platform
  • Your platform has non-uniform scaling.
vast plume
snow willow
#

so since your player is a child of the platform which has non uniform scaling, the player gets warped

#

you should rearrange the hierarchy of the platform so that it has uniform scaling (1, 1, 1)

#

the actual rectangle bit should be a child object of the platform parent object. That child object can have the scaling as necessary

#

then when your player lands on the platform, you just make it a child of the main platform parent object

#

Then you won't have to worry about rescaling the player or anything

vast plume
#

ok thanks

#

It worked don't had the problem again jet thanks

#

could you say me how i can make it so that the player can't rotate?

turbid heart
vast plume
#

yes kind da but thats normal because of gravati but i dont want the player rotating at all

turbid heart
#

If it’s a rigidbody, look at the constraints on the rigidbody component

vast plume
#

nice thx

orchid nest
#

Ok this is the last time im getting to ask before just going to reddit. I need help implementing a 2d isometric grid system, as it can now only move left/right and up/down correctly, but going sideways doesnt work as you would need to halve the value for both, and I dont know when to make the code find out you are going sideways, and thats what I need help with

#

also

#

how do I paste code

#

It just gets deleted

turbid heart
orchid nest
#

ok thanks

#
var currentPos = transform.position;
        transform.position = new Vector3(Mathf.Round(currentPos.x / gridSize) * gridSize,
                                         Mathf.Round(currentPos.y / gridSize) * gridSize / 2);
#

This is my code

#

btw

shut geyser
#

How do I put the background in the background (I don't know how to explain it)

fickle kiln
# snow willow I mean think about how you would literally do this in a real life board or card ...

hi again, I'm using this script to try and instantiate my prefabs on the canvas but although they are being created, I can't actually see them on the screen (see screenshot)

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

public class StartupScript : MonoBehaviour
{
    public List <RectTransform> prefabList = new List<RectTransform>();
    private int n;
    private System.Tuple<float, float> startPositions = new System.Tuple<float, float>(-567, -538.4f);


    void Start()
    {
        int offset = 0;
        for(int i = 0; i < 7; i++)
        {
            n = Random.Range(1, 8);
            Instantiate(prefabList[n], new Vector3(startPositions.Item1 + offset, 0, 0), Quaternion.identity);
            offset += 100; 
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}```
snow willow
# fickle kiln hi again, I'm using this script to try and instantiate my prefabs on the canvas ...

a few things:

  • Your objects are not visible probably because they are simply behind your UI background image. Basically your UI is blocking everything. ALso if your objects are ui elements then you need to be instantiating them under the canvas.
  • Why are you using a System.Tuple<float, float> instead of just Vector2?
  • Your Random.Range call is starting at 1 (it should start at 0) and using hardcoded values. You should do it like this Random.Range(0, prefabList.Length). This will always give you a valid index into the array, and won't skip the first element like with 1 as the starting number.
  • Your console window is not even visible in your screenshot so if you're getting any errors you won't see them
fickle kiln
dusty maple
#

Hi, I have this issue with rotating an object based on where my mouse position is.

#

This is my code:

        mousePos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
        currentPos = transform.position;
        aimDir = (mousePos - currentPos).normalized;

        if (equipped)
        {
            if (rb != null)
            {
                lineRender.SetPosition(0, ballSprite.position);
                Vector2 clampedEndPos = Vector2.MoveTowards(ballTarget.transform.GetChild(0).transform.position, mousePos, 3.5f);
                lineRender.SetPosition(1, clampedEndPos);
            }

            float angle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg - 90f;
            ballTarget.transform.eulerAngles = new Vector3(0,0,angle);
        }
#

Any ideas what's causing this?

snow willow
#

Also what is ballTarget.transform.Getchild(0)

#

Why not just the player's position for that

dusty maple
#

ballTarget is here:

snow willow
#

Or ballTarget position

#

And the LineRenderer? World or Local?

dusty maple
dusty maple
#

BTW I'm using a Cinemachine Virtual camera if that makes a difference

snow willow
#

It does not, unless you have other "real" cameras besides the MainCamera

dusty maple
#

Nope

#

I tested with a Draw Gizmo to see where the system was registering the mouse position to be, and it seems to be consistent with where the end of the line renderer is, and it's lined up properly with the rotation of the aiming reticle. So what I ended up doing was making the mouse invisible on startup and then just having another gameobject with a sprite renderer be where the system is registering the mouse position to be.

#

It's lining up properly now

white cedar
#

I have this two scripts, the left one is the to the camera follow the player, and the right one it's to sweep between the camera follow the player or not. But is not working D:

sharp lichen
#

You can simplify the left one

if (collision.CompareTag(“Player”))
{
   cameraFollowPlayer = !cameraFollowPlayer;
}```
#

It’s also not working because the left one doesn’t tell the camera anything, it just updates its own bool

deep urchin
#

Hello. I'm trying to get a script to rotate a object by a certain amount when I click space. I tried 2 scripts but neither one works, here are the scripts:if (Input.GetKeyDown(KeyCode.Space)) { transform.rotation = Quaternion.Euler(0, 0, 5); }andif (Input.GetKeyDown(KeyCode.Space)) { transform.rotation = Quaternion.Euler(0, 0, transform.rotation.z + 5); }What is the correct way to rotate it?

storm coral
#

can someone help me turn my chunk generation infinite, so it just expands then the player can see further?

storm coral
#

nevermind

marsh oar
#

hello, im following a brackeys tutourial, the play game one, when i drag in the script to the button, for the function, it only says monoscript, this is happening with every script that im dragging in.

#

here is my script

turbid heart
marsh oar
#

yes

turbid heart
#

can you show us the inspector so we can see what you mean by it only says monoscript?

marsh oar
turbid heart
#

and can you show where the script is attached to the button?

marsh oar
turbid heart
#

do you have any errors in your console that might be stopping your code from compiling?

marsh oar
#

no, i don't have any errors in my console

turbid heart
#

let me open up Unity and test on my side 🙂

marsh oar
#

k, thx

turbid heart
#

so the issue is usually people drag the script itself into the field instead of the object with the script?

hollow crown
#

Yes

turbid heart
#

will keep that in mind, thanks vertx!(I hope that's your cat, it's so cute)

marsh oar
bronze anvil
#

'm making a runtime level editor with isometric tilemap support.

The level editor has layers that can be added, duplicated, deleted, and reordered.
As I'm using Isometric Z As Y, every time the layer is reordered, I need to remove tiles and set tiles for all affected layers. This usually results in hundreds of actions.

If I had two tilemaps instead, I would just have to switch their positions.
But for every tilemap, I also have additional tilemaps for preview, grid, etc. so this means there would be actually 5 tilemaps per layer. The user can create any number of layers he wants, but this could be limited if needed.

What's your opinion about this issue? If I use a tilemap per layer instead of 1 big tilemap with z-axis, are there any other issues related to the draw order or performance?

potent phoenix
#

how do i make a countdown that only loads the first time a scene is loaded, before doing the updates

turbid heart
upper rune
#

Is there a way I can use the camera width as a maxX to say an object shouldnt be able to move outside of maxX?

turbid heart
upper rune
#

thanks!

#

It seems that either I can't see the full camera view or the values are slightly off

turbid heart
upper rune
potent phoenix
#

what does this mean?

#
using UnityEngine;
using System.Collections;
using UnityEngine.UI; //Need this for calling UI scripts
using UnityEngine.SceneManagement;

public class Manager : MonoBehaviour {

[SerializeField]
Transform UIPanel; //Will assign our panel to this variable so we can enable/disable it
Transform deadPanel;
bool isPaused; //Used to determine paused state
public Eel eel;
void Start ()
{
    UIPanel.gameObject.SetActive(false); //make sure our pause menu is disabled when scene starts
    isPaused = false; //make sure isPaused is always false when our scene opens
}

void Update ()
{
    //If player presses escape and game is not paused. Pause game. If game is paused and player presses escape, unpause.
    if(Input.GetKeyDown(KeyCode.Escape) && !isPaused)
        Pause();
    else if(Input.GetKeyDown(KeyCode.Escape) && isPaused)
        UnPause();

    bool isDead = eel.isDead;
}

public void Pause()
{
    isPaused = true;
    UIPanel.gameObject.SetActive(true); //turn on the pause menu
    Time.timeScale = 0f; //pause the game
}

public void UnPause()
{
    isPaused = false;
    UIPanel.gameObject.SetActive(false); //turn off pause menu
    Time.timeScale = 1f; //resume game
}

public void QuitGame()
{
    Application.Quit();
}

public void Restart()
{
SceneManager.LoadScene(0);
}
}
#

with this code

wide ginkgo
# potent phoenix what does this mean?

It means you didn't assign something to UIPanel on your GameObject that has the script attached.

Will assign our panel to this variable so we can enable/disable it

abstract olive
#

It tells you that on line 13 you're referencing something that is null.

turbid heart
potent phoenix
#

that line is just the void Start()

turbid heart
abstract olive
#

Show your inspector where you've assigned UIPanel.

potent phoenix
#

yep

#

line 13 is the Start

abstract olive
#

Then you probably have another one in your scene.

#

Type t: Manager in the search bar at the top of the hierarchy panel.

potent phoenix
#

_GM is the name of the object that has the Manager script

abstract olive
#

Do you have any other console errors?

potent phoenix
#

nop

abstract olive
#

Can you search while the game is running?

uneven rune
# potent phoenix ``` using UnityEngine; using System.Collections; using UnityEngine.UI; //Need th...

Hi, just saw Pause and Unpause, and it looks like you could simplify that.

void Update ()
{
    //If player presses escape and game is not paused. Pause game. If game is paused and player presses escape, unpause.
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        isPaused = !isPaused; // inverts the isPaused bool
        UIPanel.gameObject.SetActive(isPaused); // sets the UIPannel to be active if it is paused, or not if it't not
        Time.timeScale = someBool ? 1 : 0; // Sets the timescale to 1 is someBool is true, or 0 if it is not
    }
    bool isDead = eel.isDead;
}```
potent phoenix
#

same thing

potent phoenix
uneven rune
#

No problem.

#

Also, the original script sometimes checks if the button is pressed twice, so when doing things like that you should check if the button is down, and then inside that do if() and else. The script I gave doesn't have that minor issue tho.

upper rune
#

@turbid heart it seems to be still offset slightly

potent phoenix
#

yeah

turbid heart
upper rune
#

I used this box collider x value / 2

#
    private float maxX;
    private float minX;
    public float speed = 2/1000f;
    // Start is called before the first frame update
    void Start()    
    {
        Vector2 bottomCorner = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0));
        Vector2 topCorner = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, 0));

        

        maxX = (float)(topCorner.x - 5.514648 / 2);
        minX = (float)(bottomCorner.x + 5.514648 / 2);
        Debug.Log(maxX);
        Debug.Log(minX);
    }

    // Update is called once per frame
    void Update()
    {
        var enemyX = transform.position.x + speed;

        transform.position = new Vector2(enemyX, transform.position.y);

        if (transform.position.x > maxX)
        {
            moveDown();

        }
        else if (transform.position.x < minX)
        {
            moveDown();
        }
    }
uneven rune
#

If you use reply, rather than pinging them, it will make it easier to follow the conversation, and I can more easily help and figure out what is going on.

turbid heart
#

so your issue is it slightly exits the screen before bouncing back?

turbid heart
#

why do you hardcode your value? and you're using your collider's size, which you can see if larger than your actual sprite

upper rune
#

just hardcoded it as a test

uneven rune
upper rune
#

im very zoomed in, on that first picture

potent phoenix
#

wait a second

#

how did htat work lmao

turbid heart
potent phoenix
#

pizza your code fixed that error

upper rune
turbid heart
# upper rune it is larger but its larger by such a small amount that it wouldnt really matter

look at the answer in this thread to see how to get the actual size of your sprite
https://answers.unity.com/questions/1489211/getting-sprite-heightwidth-in-local-space.html

upper rune
#

oh nice

#

uh

#

I have no renderer on the prefab

#

the sprite is composed of many cubes

#

thats why I thought box collider bounds would work best

#

I think I know the issue

#
if (transform.position.x >= maxX)
        {
            moveDown();

        }

this is checking if the x position of the entire row of enemies has hit maxX

#

which is the center of the row

#

now I fixed it PepeHappy

turbid heart
#

great!

upper rune
#

thanks for the help!

potent phoenix
#

it doesn't even tell me what the error is anymore

#

atleast, where the error is

snow willow
potent phoenix
#

fun

upper rune
#

but it didnt

#

it only works if I have 6 enemies in the row, if I have less than that its offset again

upper rune
#
if (transform.position.x + (transform.position.x / 2) >= GameManager.screenMaxX)

I thought this would solve it

#

cause this made sense in my head ^

#

but its apparently wrong somehow

turbid heart
#

it's transform.position.x + (half the width of your grid)

upper rune
#

hmm that doesnt seem to work either

#

unless you meant grid as in the grid of enemies

#

in which case would be the transform.position.x/2

turbid heart
#

no, transform.position.x /2 is half your position,

#

i'm talking half your grid of enemies

#

so 3 of your enemies + half of the center gap

upper rune
#

riight

#

do I have to use bounds for that again?

#

cause the row is just an empty object with a bunch of enemies as children

turbid heart
#

then use the prefab or something use the bounds of it to get the width

upper rune
#

i have no idea how to get the bounds of the group

#

it seems very complicated

faint sparrow
# upper rune i have no idea how to get the bounds of the group

If you want all your object positioning relative ti center, You need to get total width required / 2 so that is fartest position, and you also need relative position of each object and i think substract it, not to remember you also need an offset for it

upper rune
#

Yeah I managed to figure out how to get the total width / 2 now but I think it doesnt recalculate the center

#

Its weirdd

faint sparrow
#

That where is relative pos take place

upper rune
#

Right

faint sparrow
#

Wait i think i stored on my phone

upper rune
#

Would be super useful!

#

otherwise I have a bounds.center to work with

#

cause when I tried drawing a gizmo to debug, the gizmo worked perfect because I could use bounds.center + bounds.size

faint sparrow
#

Couldnt find it sorry...im scroll up 5mnt with and cant find it

#

But i think i missed what you want, if you need fartest screen you can go, simply screenwidth / 2 will give you that

upper rune
#

yeah that works until one enemy dies

#

this is when using this : ```csharp
if (transform.position.x + enemyRowWidth/2>= GameManager.screenMaxX)

faint sparrow
#

Isnt that because you didnt update enemyrowwidth after some dies?

upper rune
#

right now its updating every frame

faint sparrow
#

What updating evrry frame?

upper rune
#

enemyrowwidth

faint sparrow
#

You dont need that, only if any dies you update the value

upper rune
#

yeah true, about to change it rn

honest python
#

how do I get the collision to be more precise

rocky temple
#

polygon collider I would assume

#

instead of box

honest python
#

nono

#

I meant

#

there's a small gap between the top 2 colliders

rocky temple
#

oh

honest python
#

but it still doesn't see it as if it exited eachother

turbid heart
honest python
#

what?

#

cuz I don't want to

#

if u look at the collision boxes

#

the green ones

#

there is a small gap between them

#

that is what I want gone

#

so that they're all equally spaced

signal crystal
#

Im sorry Im new in this discord, which room do i have to post if i have a question about unity?

honest python
#

depends on what in unity it's related to

turbid heart
turbid heart
signal crystal
honest python
turbid heart
honest python
#

well I can't

#

it just doesn';t rlly work for my project

wooden ruin
#

Is there a way to easily disable and re-enable an object from a script on it?

#

or just making it invisible works too

rocky temple
#

and then gameObject.SetActive(true); to reenable

wooden ruin
#

I have that, but it disables the script too

rocky temple
#

yes it disables the entire object

wooden ruin
#

So how do I have that not happen

#

If the script is disabled, it can't re-enable itself

rocky temple
#

public Color invisible; then in the inspector set this colour's alpha to 0

#

gameObject.GetComponent<SpriteRenderer>().color = invisible;

wooden ruin
#

Ok, I'll try that

rocky temple
#

and to reenable just make another public color and set it to max alpha