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

1 messages ยท Page 51 of 1

still tendon
#

(The on triggers are pseudo code. I can post some example code later if you havenโ€™t figured it out)

lament dragon
#

hey guys i am very new to unity,
i am trying to make snake game in unity using C# i have a lot of the aspects of the game working but i need to flip the body parts of the snake in a different direction.
every time the snake moves i push the head location into the list i make the body on the last location of the head, But when the snake rotates i dont know how to rotate the body part in the correct direction,

past_locations.Insert(0, this.transform.position);
        if(past_locations.Count > snake_length && past_locations.Count > 0) {
            past_locations.RemoveAt(past_locations.Count - 1);
        }
        this.transform.eulerAngles = rotation;  // rotate the snake
        for(int i=0; i < parts.Count; i++)
        {
            parts[i].transform.position = past_locations[i];
        }```



here is a picture of the problem
late viper
lament dragon
#

yes

late viper
# lament dragon yes

good, then you need to figure out how to rotate the body as you update the position of the body

#

and keep track of the point that the snake rotates

lament dragon
#

im gonna try to do that

#

thanks

sly mirage
late viper
#

you can figure that out from the inputs

#

so whenever the player presses left or right, and its a valid rotation, rotate the head and the body as it passes through that point

sly mirage
#

then would you need to store at what location the player turns the snake right?

late viper
#

yes

sly mirage
#

i see thank you

timid basalt
#

how can I make it so that whenever my play collides with a wall can it go the other way?

#

player*

abstract olive
#

What do you mean, go the other way?

#

Like reflect?

still tendon
#

If you mean bounce then create a physics material 2D, change the bounciness, and drag it onto your player

desert cargo
#

Something like that

#

Although if you're using physics you'd be better off adjusting physics material properties as owen has suggested

#

oh whoops just realized how old that question was

coral tusk
#

Hey guys i'm having issued with 2D colliders and need some help

#

mainly I am coding movement all on my own and would like to code collisions too

#

but collision checking is hard because unity seems to be running the physics engine slower than the code I write?

#

for example I have a raycast line going down from the centre of an object

#

when it is falling, the line moves higher up and off the object, even though it's meant to stay on the object?

#

does anyone have this issue?

#

in this case we can just focus on the line starting at the center of the cube, it's started falling already

#

now it has fallen for some time, forgetting about the pixel art in the background, the raycast line is not in the centre of the main object?

#

The code on the sprite is to follow the square exactly, for some reason coding the raycast directly from the box is as slow as another object attempting to follow the square?

desert cargo
#

I don't really know what you're doing though tbh

coral tusk
#

do you think that would be better than a character controller?

#

Ah im making extremely specific movements and was getting onto collisions

#

now im just gonna use the built in system

#

but idk out of velocity or the move() function

#

I was using transform.position

desert cargo
#

In the past we've just used physics but set velocity directly

#

And you can read velocity back to see what happened as the result of a collision

#

To stop objects entering each other

#

You can do full arcade physics this way

#

Just don't mess around with forces/gravity

craggy kite
coral tusk
#

that's true

coral tusk
desert cargo
#

Nah

#

You won't get collisions if you do that

coral tusk
#

oh yeah right

desert cargo
#

Only if you want it to pass through walls

coral tusk
#

whoops

#

Do I add a box collider2D with a rigid body or does the rb already have it

#

I wont for now

modest cargo
coral tusk
#

probably true but every time I find a unity guide as a beginner I find some dodgy things

#

I feel like I know most of what I need for now, im just learning to use velocity atm

#

oh rigid body automatically frame independent, that's nice

split portal
#

Hey anyone know how to program tilemaps?

modest cargo
split portal
#

I mean i want to program them, procedurally

modest cargo
#

I'm not much help with that, but I guess a good starting point is why or what functionality do you want to get out of it

split portal
#

to draw fucntions on a screen

#

and then have interactivity with each tile

coral tusk
#

I feel like im getting friction for staying on the ground with rigid body, how do I avoid this

lapis fiber
#
public GameObject prefabObject;
private BoxCollider2D boxCollider;

void Start()
    {
this.boxCollider = prefabObject.GetComponent<BoxCollider2D>();
    }
``` how do i then use this.boxCollider to detect if there is an object is intersecting the the BoxCollider2D?
frail halo
#

My player is not interacting with other rigidbodies, despite the fact that I'm pretty sure it setup all of them the same way

craggy kite
toxic anvil
#

why dont i see my score and hp in this even though i can see thoses when i play it is not in fullscreen

craggy kite
#

I do not see any score, can you rewrite your sentence. Do you see it at some point, only in fullscreen or not in fullscreen?

toxic anvil
#

the score is hidden behind the asteroid lol and it doesnt appear in fullscreen

#

the score and hp work but whenever i make it full screen its not visible tho its still working since i tried pausing it and seeing the score and in console as well.

#

@craggy kite

craggy kite
#

@toxic anvil What happens if you resize the window instead of fullscreen, does the score glitch or scroll outside the view?

coral tusk
#

can I easily slow down to 1fps for debuging purposes in game view?

craggy kite
#

targetfps should help you in script

toxic anvil
#

oh it still doesnt show

craggy kite
#

targetFrameRate

toxic anvil
#

its like its getting zoomed in

craggy kite
toxic anvil
#

it seems the score and hp are out of camera

#

now i kept them inside the camera

#

and its annoying

#

whenever i open unity camera changes it place

#

;-;

#

now it looks something like this

#

would be great if u know how to stop this camera changing its place

craggy kite
#

The camera always fits your game view

#

You have to set your UI to dynamically change its width to the width of the screen like so:

#

Be sure to checkout a basic tutorial on Unity UI to learn how to set it up.

toxic anvil
#

is canvas ui?

#

or just the text

craggy kite
#

the canvas should adapt to the view anyway if you dont change the default settings. then you have parented the UI items like images and stuff, those you have to set to either resize or just stick to left top and right top, again, checkout a simple starter tutorial, it will tell you how to do it in a better way than me here writing it ๐Ÿ˜„

toxic anvil
#

oh thank you

#

i did set it to space view camera

#

which setted it up but then my text wasnt visible there

#

so i changed it to world space

#

let me just restart the game and see if it changed itself again lol

craggy kite
#

World Space will make your UI float in 3D space, not sure if you want that ๐Ÿ˜‰ ScreenSpace should be the right thing

toxic anvil
#

not sure about that but screen space did the opposite ๐Ÿ˜‚ i had change the z of the camera - to see the text

#

i even asked the question here about that lol

craggy kite
#

World Space is like a gameobject with a 3d plane showing your UI. Screenspace is just on top of you rcamera image, which you want I guess.

toxic anvil
#

now it didnt change luckily and i hope it wont ever again ;-; now i need to see the game over thing

#

yes i know about screen space and thats why i changed it to that but it didnt work well ;-;

craggy kite
#

Then you might have some z fighting with the rest of your 2d game assets. Just create a layer for the UI and set its depth above everything

toxic anvil
#

for some reason world space works good for this ๐Ÿ˜‚

#

i just changed my camera z to -10 and canvas to 1 and world space and it worked

craggy kite
#

I hope it keeps working, I barely believe it will in the scope of your project ๐Ÿ˜‰

#

As soon as you get into different screen sizes, you will get some surprise ๐Ÿ˜‰

toxic anvil
#

different screen sizes?

craggy kite
#

I got a 24:10 screen, you got 16:9 or 10, some might even have 4:3

toxic anvil
#

oh

#

i see what u mean

#

now i dont know what to do about that ๐Ÿ˜‚

craggy kite
#

go screenspace, watch a tutorial about dynamic size of UI, do it the right way, be happy ๐Ÿ˜„

#

https://www.youtube.com/watch?v=95q79j0lNYA might be old, but not that much changed for the UI in case of resizing

Unity3D Tutorials | Social Media and Website Below + Downloads.

Social Links: https://socialqr.xyz/U3DwScott

Unity3D With Scott | UI Tutorial - How to scale the canvas for all screen sizes.

Thank you for watching my video.
Make sure to leave suggestion in the comment section.
Don't Forget to Subscribe for more tutorials.
--------------------...

โ–ถ Play video
lapis fiber
#
IEnumerator fruitWave(){
        while(true){
            yield return new WaitForSeconds(respawnTime);
        spawnFruit();
    }

im using this to spawn an object in a certain area, but how do i make it so that it wont spawn if there in an object that exists between x(5, 8) and y(3)

toxic anvil
#

make an if statement

toxic anvil
lapis fiber
near tree
#

so how about them pixel perfect problems, amirite?

sharp herald
#

u rite

smoky plover
#

hi everyone, dunno if it's related to 2d-code or general-code, but here's the problem I've been trying to figure out for a couple of days (longpost incoming):

I'm making an escape-room style App (the whole thing is UI on a Canvas, rather than a normal 2D Game), which has various views, buttons that trigger stuff, very little generated UI elements, etc. (think Hearthstone main menu with all the expansions, card collection, etc UI stuff).

And thinking in general terms, I'm looking for the best practice for switching between views (screens with UI elements), reading and sending data from input fields to different scripts, showing messages on screen, reacting to buttons, etc.

Singleton was the first bet, like viewManager that just has references to ALL views/screens, and then activates/deactivates them based on function calls. But it's obviously infamous, + I don't really like it myself, + giant viewManager sucks.

Looking at the "new" ScriptableObject events that can Invoke OnShowViewAClick, and then some small controller for ViewA would listen to that and activate ViewA seems like a better option, but then again it seems like I'd have to create an event for basically every view switch, and that probably sucks too.

Is there an approach I'm missing, or a better way to activate/deactivate between a bunch of views?

craggy kite
#

It really depends on your project @smoky plover like how your games are setup. If you have like tasks, I would go and make a TaskManager Class that inherits all callbacks or whatnot that need to be completed for example, inside that you got that array of Tasks that can be type of input, buttons, puzzle or whatever. So you get one taskmanager for each escape solving part. But thats just one guess of a dozen, if we do not know what you will do. Maybe you got an inventory too? Maybe tasks rely on each other?

smoky plover
#

thanks, but this suggestion probably comes handy to a later stage of the game.
Just to make it simpler: I'm trying to build a complex multi-page UI, with a bunch of Views, and the sole crisis I'm having is to figure out what's a good way to change Views โ€” which architecture to use for this

craggy kite
#

what is the hierarchy of it? Is it like cross every hierarchy from view to view, or is it more like a tree you can go back and forth?

smoky plover
#

say you have an "Tutorial" section, where there's 10 Views that tell you what to do, and there's buttons "back/forth" on the bottom to flip through these

#

after that you get a "Input Your Name" View Group, with 2 pages โ€” "Input" view (simple input field), and on submit this one should switch to "Confirm Name" View, which has like a back button and a GoToSomeNextView button

#

what is the hierarchy of it?
a combination, you will follow a single line (e.g. Tutorial), then it's some screens you can back-and-forth to ("inventory" -> look at ItemA with some text -> back to "inventory" -> notepad View -> back, etc), then again some single storyline to bring you to the "Game Over" view for example

craggy kite
#

Well then its depending on the case I guess, inventory is one set of views and overlays, tutorial is one set of views, and then you gotta hardwire those navigation paths I guess. There does not seem a one for all solution for more than one UI navigation concept, tbh.

smoky plover
#

I guess I could use an event system:

  • Invoke(OnTutorialOver)
  • EventListenerI(OnTutorialOver) -> StartInventoryStage
#

but then within the "tutorial" section, there's still need for some singleton to "flip" between tutorial sub-views

craggy kite
#

you might want to separate the visual from the code a bit. Like, let the buttons to their work for example and just handle states in the code, triggered by the buttons too. Maybe just write down your hierarchy on paper and see what makes sense to group or not

rocky temple
#

if I were to make a moving platform, would using the animation system or coding the movement be better?

craggy kite
#

phew well, that depends on what the platform is going to do. Is it going to loop or will it be dynamically affected by other stuff

rocky temple
#

I'm planning on it to just be able to move from one point to another and then back

craggy kite
#

You can make some nice animations with the animation tool, not sure about physics being affected. I did a little script with a parent transform as a target and then just lerp from a to b to a looping, so you could just use the target to dynamically change the path and so on. Again, depends on your need

rocky temple
#

alright sounds good thank you

craggy kite
#

yw ๐Ÿ™‚

smoky plover
#

alright thanks, makes sense ๐Ÿ™‚ I really need to draw this on paper to think straight

still tendon
#

I keep getting an error with this code the error is
Assets/Scripts/PlayerMovement.cs(11,1): error CS1519: Invalid token '{' in class, struct, or interface member declaration
does anyone know how to fix

still tendon
#

oh

#

where

abstract olive
#

There should always be the same amount of { as there are }

still tendon
#

k

abstract olive
#

Try to find it, your script isn't that long.

#

Every open { has a matching }. Pair them up and see which one is the orphan.

still tendon
#

thx

storm coral
still tendon
#

fixed it

#

thank you

storm coral
#

another very strange thing is that it works fine in the play window, but not in the executable

wooden ruin
#

I can't figure out how to change the color of a line renderer, does anyone know how? also it has to only use code, because a new one gets created and destroyed every frame

lucid plaza
#

The line renderer has a material, so you can change the color of the material

storm coral
#

please help i cant figure this out!

proven trout
#

I was screwing around in unity and tried to make a square launch to the right but it says this error

#

Assets\Movement.cs(9,12): error CS1501: No overload for method 'AddForce' takes 3 arguments

#

what am I doing wrong

#

this is all that I wrote

#

does Rigidbody2D work different from Rigidbody or something

#

please help

native pelican
#

I have an issue with UI elements inside a Scroll View where they don't take the full width of the screen when I set the UI Scale Mode of the Canvas to Scale With Screen Size instead of Constant Pixel Size.

#

So, what I want to remove is the space on the left and right sides, or these two areas highlighted in red.

#

It should look like this.

lean estuary
#

Use content size fitter to adapt container to present elements sizes using their preferred size.

dense creek
#

๐Ÿ‘‹ I have a Scroll Rect on a UI element with the content set to itself (the thing that scrolls), Viewport set to the parent, and scrollbar set to another element in the parent.
For some reason the scrollbar seems to reset during gameplay. I notice it happening when another UI element updates.

#

Is there a way to prevent it from scrolling back up?

still tendon
#

i just made the script for the idle animations and when i save it in unity i just get tons of errors can anyone help me

modest cargo
still tendon
#

yes but i dont really understand them

#

i can send you a screen shot of all the erros

#

*errors

modest cargo
#

We certainly would have to see them to help

still tendon
#

k

lean estuary
#

@still tendon Select Edit > Advanced > Format document. And look what shortcut it uses while you're at it for the future. Then remove extra braces across the script

storm coral
#

Please help!! my tilemap's collider does not work if i add it to my script! what could be causing this? code: https://paste.mod.gg/omuguqusag.cs
The strange thing is that it works fine in the play window, but not in the executable

ruby jetty
#

Okey so like I wanna make a sorta Neko Atsume style game about beetles and like I have no coding experience and I have no idea where to start

#

As far as I know there arenโ€™t any tutorials on what I want to make and like I have no idea what to do lol

lean estuary
#

@ruby jetty Look up isometric 2d game tutorials.

rocky temple
#

how do I turn these on/off in script

heavy token
rocky temple
quick dock
#

yo its my first time using unity and C#, and im trying to make basic left to right player movement right now, following a tutorial, but everytime i save it unity gives me the error "Assets\scripts\playerMovement.cs(5,13): error CS0246: The type or namespace name 'RigidBody2D' could not be found (are you missing a using directive or an assembly reference?)"

#

my code:

#

using UnityEngine;

public class playerMovement : MonoBehaviour
{
private RigidBody2D body;
private void Awake()
{
body = GetComponent<RigidBody2D>();
}

private void Update()
{
    body.velocity = new Vector2(Input.GetAxis("Horizontal"), body.velocity.y);
}

}

storm coral
#

Please help!! my tilemap's collider does not work if i add it to my script! what could be causing this? code: https://paste.mod.gg/omuguqusag.cs
The strange thing is that it works fine in the play window, but not in the executable

snow willow
#

Rigidbody2D is the correct capitalization

storm coral
#

Please anybody help! or if you cant, please reccomend to me somewhere to go where people can!

subtle geyser
#

Can anyone recommend a good architecture for associating game objects with tiles on a tileset? I'm working on a small roguelike project and am struggling to determine how best to approach the interaction between the player and the tiles on the tilemap.

Currently I'm using a dictionary to store positions as a key and tile types (floor, wall, enemy, item, etc.) as a value. This is checked against whenever the player attempts to move to that tile.

I've also got a separate list that also contains the positions for when I need to loop through the map by index (this at first seemed redundant but my understanding is a dictionary wouldn't work for this purpose)

My main concern is how best to access properties of the enemy, item, etc. that the player would be interacting with. In this project enemies don't move so should I be storing that data in enemy / item gameObjects or the tile itself? Is there a better way to go about this? Any insight would be helpful.

storm coral
#

im not sure exactly what youre saying, but what I use in my game im making is a WorldToCell operation, built into unity's tilemap thing, cs TilePositionOnGrid = (UsedTilemap.WorldToCell(Vector3 TilePositionInWorld);

#

look it up in the docs its pretty cool

subtle geyser
# storm coral im not sure exactly what youre saying, but what I use in my game im making is a ...

Thank you for the tip. I'm able to access the tilemap tiles without issues as well as their positions. My issue is that I'm not sure the best way to go about interacting with the gameObjects that spawn on some of those tiles.

Say I have my script that generates the map and sets the tiles within the tilemap. But then I have a separate script that chooses random eligible positions and spawns enemy GameObjects on top of those. It also sets a custom property of that tile to "enemy". I'm wondering specifically how best to have the player interact with those enemies.

If the player bumps into an enemy space, should I try to do a GetComponent based on some association with the tile? Should I raycast to that enemy to get its data? (things like health, attack power, etc.). That's what I'm struggling with.

#

Basically I can get as far as making the map, placing the enemies, and moving the player, but having those things interact with each other is where it can get messy so I want to make sure I'm setting up good architecture so I'm not regretting it later on.

storm coral
#

Enemies should proboably have some sort of trigger collider, how i would do spawning to make the rest easier is to make each enemy type a prefab, and instantiate it at the coordinates the script tells you

subtle geyser
#

That's currently how they are spawned. A collider might work in this case if nothing else. I'm also curious how this was done back in the day in the original Rogue, etc. as that might provide some additional options I hadn't considered..

pearl geyser
subtle geyser
# pearl geyser A lot of projects take the physics approach of putting colliders on anything the...

Appreciate the input. And yeah while I can see that being the go-to in a lot of cases I agree that there surely are less expensive methods out there. I did come across this which is probably the direction I'm going to go https://roguesharp.wordpress.com/2014/08/30/tutorial-6-roguelike-combat-using-roguesharp-and-monogame/

Edit: This tutorial was written using RogueSharp 1.1 so if you want to follow it exactly make sure you are using that version. After RogueSharp version 2.0 released there were some changes to the wโ€ฆ

#

Basically uses a Combat Manager class to check if an enemy matches the tile position you're trying to engage with and resolve combat within that class

pearl geyser
#

Yeah, as long as you're not simulating thousands of enemies at once that's probably completely fine for something that's only happening once per turn.

subtle geyser
#

Yeah its like maybe 10-15 per screen, and its turn based so it shouldn't be an issue

delicate moat
#

im not sure why this is happening, but im trying to program a door where when the player stands inside of a wire box and press 'E' yo would be transferred into the next room. but for some reason I cant see the wire box when i try to fit it to the doors size. it just doesn't show up when i mess around with the x and y values. I can send a screenshot of the code and setting in unity if that would help.

subtle vessel
granite plank
#

hello, just curious how to use the onTriggerEnter2D collision function, do i put this on the object that is going to enter the other object?

subtle vessel
delicate moat
#

heres the code

subtle vessel
#

in your screenshot width and height are both 0. Did you try setting them to higher values?

snow willow
#

also do you have gizmos enabled?

subtle vessel
#

and have the gizmos enabled for the door script specifically (sometimes some of my gizmos seem to get randomly disabled)

delicate moat
#

i dont think i have gizmos enabled, thank you guys so much! ๐Ÿ™‚

subtle vessel
granite plank
#

so im making a fishing game right, the hook has the collision script for OnTriggerStay() while its over a fish. the hook is a 3d object while the fish is 2d. its not printing out that its colliding when the code is ran

subtle vessel
#

the 2D and 3D physics systems don't interact with each other

#

if you have a Collider2D, it won't collide with a Rigidbody. Same with a Rigidbody2D and a Collider

snow willow
granite plank
#

okay i think im just confused because i dont know what to do? the hook has to be 3d because im using it for something else that requires it to have a 3d box collider. so then for the 3d fish i should instead of 2d box collider just have a normal box collider?

subtle vessel
#

you should choose one physics system and use it for everything. It sounds like you want to go with 3d, so you should use a 3d box collider for everything

granite plank
#

and rigidbody?

snow willow
#

yep

subtle vessel
#

and rigidbody

#

not rigidbody2d

snow willow
#

I've never seen a game that uses both the 2d and 3d physics engines at the same time but that is also technically not a problem at all, as long as you're aware the two will not directly interact. I've always thought it might be interesting to have a game where a single object has, for example, a 3D dynamic rigidbody and a 2D kinematic rigidbody and let the two physics engines sort of interact like that

granite plank
#

im getting this error:

snow willow
#

I'll make a prototype for fun at some point

granite plank
#

it has to be 3d because its for mobile and im using a ray for touch controls to control the hook but the fish is 3d

snow willow
#

but you probably switched to the 3d rigidbody

#

you need to switch the code over too

granite plank
#

oh thank you!

delicate moat
#

i enabled gizmos and i still cant see the wire cube

subtle vessel
delicate moat
#

yes

subtle vessel
#

oh, you have a typo in your code

#

you misspelled OnDrawGizmosSelected

delicate moat
#

oh

subtle vessel
#

you have an extra o in Gizmos

delicate moat
#

i cant believe i over looked that, thanx man

granite plank
#

hmm its still not printing out if it enters/exits colliding

subtle vessel
#

paste your code?

granite plank
#
public class HookCollision : MonoBehaviour
{
    void OnTriggerEnter(Collider col) {
        // On Enter
    Debug.Log("Enter");

    }

    void OnTriggerExit(Collider col) {
        // On Exit
    Debug.Log("Exit");
    }
}

snow willow
subtle vessel
#

okay, and you're looking at this from a 2d perspective? Are you sure the two colliders are overlapping in 3D space?

snow willow
#

yes the rigidbody is required - it can be Kinematic if you don't want the object to be simulated by physics

granite plank
#

all 3 of those are checked and i have all of those correct. i thought of the same thing when the hook wasnt on the canvas with the fish but ive been trying it with it in the canvas and it doesnt work either

subtle vessel
#

wait, the fish is on a canvas?

#

as in, it is a UI element?

granite plank
#

yes

snow willow
#

oh dear god

granite plank
#

XD

snow willow
#

lol sorry

granite plank
#

no ur fine its just funny because the hook has to be 3d

#

can i move the fish off the canvas its just a 2d sprite

snow willow
#

it's just - I've never seen someone mix the 2d and 3d physics engines while also mixing up world space and screen space objects

snow willow
#

please do

#

and then, double check what Tachyon asked above - that the colliders of the objects are actually overlapping in 3d space

#

take your editor out of 2D mode if it's in 2D mode

#

it will be easier to visualize

granite plank
#

hmm so the fish has a ui healthbar and its not showing now because its not on the canvas is there a way around this?

#

yay its working btw thank you so much so now i just gotta get that ui back on the fish, because its a 3d object its like the hook and i can move the fish now too its kind of a mess

snow willow
granite plank
#

okie cool

near raptor
#

Does anyone have experience with the player pointing towards the mouse in 2D? Its cause I'm having trouble with the normal camera or cinemachine while using the code to make the player look towards the mouse. I have already searched a ton of different codes and logic and none of them work. I have also tried and not use cinemachine, use different cameras and nothing works. Every time I try it out I get some very jittery movement

desert cargo
#
  1. Get mouse position (might need to raycast this, I'd use Plane.Raycast in combination with camera function like ScreenPointToRay)
  2. Get player position
  3. Get direction from player to mouse (mouse position - player position)
  4. Get the angle of that vector from vertical Vector2.SignedAngle(Vector2.up, direction)
  5. Apply this angle to your player transform.rotation = Quaternion.Euler(0, 0, angle)
#

If you want it to be smoother you can apply SmoothDamp to that angle value

near raptor
desert cargo
#

Yeah.

near raptor
#

Okay Iโ€™m gonna try it out thanks for the help

modest abyss
#

So I have this laser and it moves in a circular path around the mirror. I want to restrict its movement when it makes an angle of 30 along the x axis with the mirror. How do i do that?

onyx kestrel
modest abyss
#

Nicee, umm how do i clamp it tho? @onyx kestrel

fierce sluice
#

Use a branch statement to see if the angle is at 30 degrees and set it to itself if so

modest abyss
#

umm can you tell me how do I set it to be at 30 degree ? been struggling with that ;-; @fierce sluice

fierce sluice
#

The issue Iโ€™m thinking about is actually finding the angle, which if you donโ€™t have might be tough. (Though, I havenโ€™t been coding with unity too long. Thereโ€™s probably a function that would help tremendously with this)

I wish I could help more with functions that might help, but I actually donโ€™t know if the angle isnโ€™t already known. Thereโ€™s also probably a mathematical equation you could use for finding the angle, but Iโ€™m not sure what thatโ€™d be right now.

But I do know you can set the rotation. Youโ€™d probably be able to get away with setting the rotation if the rotation gets at a certain spot.

modest abyss
split portal
#

HI. Anyone know how to put 2d collider on 3d object so it doesnt follow rotation?

#

Does it have to be through scriptin

arctic cloud
#

Hi, does anyone know why turning 'Is trigger' removes collider of the object

split portal
snow willow
split portal
snow willow
#

You get the reference from the collision callback function

arctic cloud
#

Help pls. The thing is that when triggers for two cubes are turned off, they collide perfectly, but triggers are on, they don't collide

compact knoll
arctic cloud
#

both of them have colliders

#

and i need a trigger when one cube collides other

compact knoll
#

if you are trying to run something when two solid colliders touch you can use OnCollisionEnter2D. Triggers don't behave like solid objects so it doesn't sound like that you would want to use triggers in this case

arctic cloud
#

I guess I'm missing something very plane, but there are two collidable objects, but when I click on "IS TRIGGER", on both objects, they don't collide

hollow crown
#

triggers are not solid

compact knoll
#

Right, this is because when something is set to be a trigger it won't act like a solid object anymore

arctic cloud
#

Oh, thank you. Is there any solution to this, despite creating empty trigger?

hollow crown
#

Don't use a trigger, just use normal colliders. boxfriend already mentioned the appropriate callback for them.

arctic cloud
#

thanks, now I get him

#

thank you everyone!!!!

craggy meadow
#

Hi, I have been struggling to get rid of jittery sprites in my game. I've been pulling my hair out for past 4 weeks trying to fix this issue. So I cooked up a small show case project with my player that can only move left and right.
I'm using a state machine to handle my player and only states that I included in this project is idle and move state. I'm also using cinemachine and pixel perfect camera and my jitter appears only when my player starts moving.
I'd appreciate if someone could take a look at it.

here is link to the project zip file: https://drive.google.com/file/d/1qxWdmzwIZkBmukhy4x7aFuZgkVYEOB7E/view?usp=sharing

Also if you need any more info about anything let me know.

modest cargo
craggy meadow
#

also I tried moving my player with RB2D.AddForece() but it didnt help as well

modest cargo
#

All physics forces should be in FixedUpdate
Camera should be moved in LateUpdate unless there's some specific reason not to

#

RigidBody Interpolation should generally be set to Interpolate

#

I think that's the usual bucket list

craggy meadow
#

right tried doing all that but it didnt yield any results

#

any other ideas ?

modest cargo
craggy meadow
craggy meadow
#

@modest cargo hey are you looking into my project or you dont have the time for it now?

modest cargo
#

This seems like something I'm going to butt heads with in my own projects sooner or later

craggy meadow
#

alright let me know if you get any developments

native pelican
#

I have an issue with UI elements inside a Scroll View where they don't take the full width of the screen when I set the UI Scale Mode of the Canvas to Scale With Screen Size instead of Constant Pixel Size.

#

So, what I want to remove is the space on the left and right sides, or these two areas highlighted in red.

#

It should look like this.

modest cargo
#

People on forums were claiming it was fixed even earlier than that which is really weird

#

If someone else wants to give it a go, that'd be cool

native pelican
#

Unfortunately that suggestion didn't work. The space on the sides is still there even after those changes.

lean estuary
#

@thin crater Don't cross-post, please.

thin crater
willow current
#

Okay so I've made a wall jump feature but I'm not sure how to make the player bounce away from the wall when they wall jump

Heres the code
https://paste.myst.rs/vqk4zc47

snow willow
#

you can use that to determine wall jump directionn

willow current
snow willow
#

up to you

willow current
#

because the wall jump mechanic is outside of it

snow willow
#

might make sense then yeah

willow current
#

also, how do I like use it?

snow willow
#

?

willow current
#

do I just put it in the place where rb.velocity.x is

still tendon
#

Im working on a camera follow script and whenever i hit save it it has a NullRefrenceExpictation error and instead of showing the player it shows the sky box can anyone help me

opal socket
#

Restart your unity

#

And you are misusing lerp

modest cargo
#

Even though it's not correct, unity's own video tutorials instruct people to lerp like that ๐Ÿ˜”

fickle moon
#

Hey guys does anybody know a good tutorial about an 2d inventory system?

woeful sentinel
#

It would much faster if you just google them

#

trust me

rough flame
#

ok so brain go BRRR tryed animation got run and idle working but then jump gose brrr this is the code and it just loops jump animation

rose valley
rough flame
#

wot im not big brain

split portal
#

How do I check which collider im overlapping with

#

i want to access the other objects material

#

Ive got an OnButtonInput unit, so when the the player presses "Fire 1" I want to check whuch object it is and change its material

rose valley
visual musk
#

Hello, i have a problem can someone help me ???

#

so i have a gameobject, rigidbody2d is applied to it

visual musk
#

when i use rb.moveposition it worked just fine, but when i use rb.moveposition from another script it didnt worked, even tho i have referenced it the rightway

#
// I referenced rb with this
rbPlayer = player.GetComponent<Rigidbody2D>();

// and i want to move position it didnt worked
rbPlayer.MovePosition(new Vector2(player.transform.position.x + arah.x * ms * Time.deltaTime, player.transform.position.y + arah.y * ms * Time.deltaTime));
#

what's wrong ?

rough flame
#

i dont think my Grounded Bool isnt working becuase even when i am grounded it dosent jump i think i got the animation working now?

visual musk
#

it's even odder, because when i used

rbPlayer.mass = 100f

it's worked

rough flame
snow willow
#

but also - can you be more specific about "didn't work"?

#

what happened and how was that different from what you expected?

rough flame
#

Ok

#

So when i press play on unity The run and idle animation work and i can move but it is not allowing me to jump and the grounded seems to not be check on when i am grounded on the ground and my Tag ground is on my ground platform

snow willow
#

how are you performing the check?

rough flame
#

it dose seem like that

#

Ah

#

like that

snow willow
rough flame
#

yes

snow willow
#

OnCollisionEnter2D

#

you have onCollisionEnter2D

rough flame
#

๐Ÿคฆโ€โ™‚๏ธ

#

hm still no jumping

#

i fixed it :))

manic ruin
#

im hello guys i have probleme in coding, when i do "Instantiate" to an image it just spawn but i cant see it bcuz its not in the canvas how can i make it spawn auto in my canvas?

snow willow
#

or as the "parent" paramater in any form of Instantiate that takes a parent parameter

manic ruin
#

ow okiiii ima try it thnx

cerulean glen
#

How would I get the top left and top right corners of a camera POV?

wide ginkgo
cerulean glen
#

Yeah, but how does that work? Ive never understood the method

wide ginkgo
cerulean glen
#

Yeah

wide ginkgo
#

The bottom-left of the viewport is (0,0); the top-right is (1,1)

So if you want top left you would give it new Vector3(0,1,0)

#

var topLeftPosition = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));

cerulean glen
#

Thanks :)

#

That canvas is fitted to the camera

#

And it doesnt show up at the game

#

the hell

#

Oh, it created it on the z axis

#

the heck

#

ah

#

i see

carmine stag
#

so, i have an audio manager

#

but i need to hook it up to a slider

#

so people can adjust volume

#

how?

carmine stag
snow willow
#

around 7 minutes in

carmine stag
#

ok, will take another look

manic ruin
#

can some one help... im getting an error but idk how i solve it.; and i have no probleme in my script

#

and i have the spawner assigned

#

and the code have no error

#

plz some one help

#

when i play it some times work and some times give me that error and stop the function

#

...

#

some one help?

reef dune
#

maybe you destroy it somewhere?

manic ruin
#

@reef dune no

reef dune
#

send some more of your code

#

maybe the issue is somewhere else in the code

manic ruin
#
public GameObject spawner;
        if (isWood)
        {
            SetParent(Instantiate(plank, spawner.transform.position, spawner.transform.rotation));
        }
        else if (isPlank)
        {
            SetParent(Instantiate(stick, spawner.transform.position, spawner.transform.rotation));
        }
        else if (isStick && isStone)
        {
            SetParent(Instantiate(axe, spawner.transform.position, spawner.transform.rotation));
        }
public void SetParent(GameObject PlaceToSpawnIg)
    {
        PlaceToSpawnIg.transform.parent = newParent.transform;
    }
#

@reef dune there is the most of it

reef dune
#

im confused

#

where is your main function

#

where did you declare the variable spawner

manic ruin
#

i just copied the inporten part of the code

#

@reef dune let me send u all the code 1m

reef dune
#

dang idk, your code looks weird

manic ruin
#

yes ;-;

#

@reef dune it works normal but some times it just say that error for no reason

reef dune
#

maybe you did some weird shit with the event system

manic ruin
#

@reef dune nah

#

@reef dune there r other ppl had my probleme but there is no answeare in google

reef dune
#

welp

manic ruin
#

yup

#

idk what im gonna do now

late viper
manic ruin
#

@late viper ik ive all ready checked so many times and dident find

late viper
manic ruin
#

okii

#

@late viper ow wth i found another one

#

oof

#

lol

#

thnx @late viper

#

idk how i didnt find it

late viper
#

thats why you don't manually check these things ๐Ÿ˜„

manic ruin
#

@late viper lol i dident know that i can do that i were searching for a way to do that well u teached me smth lol

late viper
#

you can also click the magnifying glass in the search bar to filter by type

manic ruin
#

ow

#

ow

#

thnx ^^

minor barn
#

Question. I'm spawning a random number of buttons from 1-6. I'd like to arrange them evenly across the screen.

minor barn
#

Sounds like what I'm looking for

minor barn
#

Related question: Is there a guide to bringing a UI element to the top of the render order when you mouse over it?

delicate moat
#

Hi, im trying to create a script where if a player walks into a wire box and presses "E" then they enter another Scene. Im having trouble with it because it doesnt seem to want to switch from scene to scene. im not sure why. if you could give me some tips that would help, thanks!https://paste.ofcode.org/3bMUFvzrHgLNLDcPQQJ7uW9

visual musk
#

SO i'm trying to make a button which will trigger a platform to move, i want to use only one button ui to control the platform, how do i make the button to interact with the nearest gametag ????? I've searched in google with no clue

still tendon
#

Thats of the top of my head so not sure if it'd work, sorry

still tendon
minor barn
#

I'm also using horizontal arrangement, so that would move the card to the front of the line.

still tendon
#

ah yeah I see

split portal
#

Anyone know my one way colliders dont work?

sweet swan
#

@split portal make sure its parent isn't a canvas

#

physics on ui components are a little unpredictable

turbid heart
#

ui components shouldnt even have physics though

sweet swan
#

mm, which is why i'm concerned about that recttransform

split portal
sweet swan
#

create a new gameobject and copy all the components over? make sure it's not a canvas

split portal
#

its just a square sprite, with a edge collider and one way effector....but some how I cant get the 1 way functionality to work. it blockes both sides of the edge

sweet swan
#

oh mb this looked like a recttransform

split portal
#

I thought maybe it was soemthing to do with collision layers??

sweet swan
#

possibly, but i'm assuming you've set the collider mask properly in the effector

split portal
#

Does edge colliders or one way colliders can have diffrent behaviour on different layers?

sweet swan
#

and that the transform hasn't been rotated

split portal
sweet swan
#

there shouldn't be any difference between collision layers besides what contacts are allowed in project settings

split portal
#

Damn.

#

it works like an edge collider.....but the effector is non functioning

sweet swan
#

some things i'd try:

  • check all collider positions with gizmos in scene view
  • make sure that the other collider doesn't start inside of the edge collider when you're testing
  • see if enabling one way grouping does anything
#

i'd also suggest checking the layer collision matrix, but it sounds like the edge collider itself is working so i doubt that's the problem

split portal
#

k.

#

everything is checked

sweet swan
split portal
#

new one

#

how do i delete layers?

sweet swan
#

should be in project settings -> physics2d

split portal
#

k... i guess you just delete the name

high falcon
#

is asking about modding games allowed in here?

gritty palm
#

Assets\Scripts\NumberWizard.cs(16,6): error CS1513: } expected
im not sure why there is an error whats the problem?

abstract olive
#

Your main problem is an unconfigured Visual Studio. Set it up following the #854851968446365696 guide. It'll highlight the errors.

gritty palm
#

@abstract olive which one do i choose vs 2019 or code?

abstract olive
#

VS. Visual studio code is another program.

#

Though, if you install VS through unity Hub, it'll auto set it up for you. But just try out the guide.

delicate moat
delicate moat
#

theres no errors or anything so im not sure why its not working

delicate moat
#

never mind i got it working

delicate moat
#

I forgot to change the layer rather than the tag

balmy pollen
#

Hey guys, can someone help me with the blend tree? I want to change animation (same character) stopped, but want to do that when I click on the corresponding approximate angle, as shown.

#

I want to perform the character's attack animations
but with the mouse click

#

?

heavy token
# balmy pollen ?

go at it step by step: You need to compare the position of your character to the position of the mouse. If the mouse.Y position is higher than the player.Y position then you know it's one of the 4 upper pie pieces. If the X position is higher then it's one of the 2 pieces at the top right. If the mouse.X position is higher then the mouse.Y position then you selected the east-east-north slice.

balmy pollen
#

my problem is with the blend tree

cerulean glen
#

Why is the circle sliding even when you let loose of the left/right key? Ill post the code in a sec

#
void Update()
    {
        float h = Input.GetAxis("Horizontal");

        Vector3 tempVect = new Vector3(h, 0, 0);
        tempVect = tempVect.normalized * (speed * Time.deltaTime);

        this.gameObject.transform.position += tempVect;
    }
balmy pollen
cerulean glen
#

No uhh, I am looking for help

balmy pollen
#

ohh ok

balmy pollen
heavy token
#

@cerulean glen nvm I think you just have to remove .normalized

cerulean glen
#

That worked, thanks!

heavy token
#

.normalized returns a vector with a length of 1 unless it's 0. Your input settings will reduce the value of GetAxis() over time once the player releases the key. So even if GetAxis returns 0.001 .normalized will set it to 1. You could also solve the problem by setting the 'delay' value of the axis to 0.

balmy pollen
#

?

heavy token
#

that was for Collbrothers, I don't know much about blend trees

balmy pollen
#

tyvm, ty

subtle vessel
balmy pollen
#

yes i have.

#

I try almost the all code to change blend tree animation

#

like anim.SetFloat("horizontal", attack.x) ; anim.SetBool("Attack", true) ; Play("Attack") .....

#

anim.SetFloat requires speed, but i wanna do it stopped

#

anim.SetBool, just give a only option to all my animation

subtle vessel
#

can you post a screenshot of your blend tree?

balmy pollen
#

sure

subtle vessel
#

and the inspector too?

balmy pollen
#

sure

subtle vessel
#

in order to switch states between items, you should be using anim.SetFloat("AttackX", attack.x); and anim.SetFloat("AttackY", attack.y);

balmy pollen
#

whats the variable attack? Vector 3?

#

or Vector 2?

subtle vessel
#

it should be a float of some kind. I was just copying the way you seemed to be using

#

sorry, the attack.x should be a float

#

or you could have float attackX; and calculate that instead of having a vector anywhere

#

anim.SetFloat("AttackX", myXAttackValueAsAFloat);

balmy pollen
#

but this float will change the value in the blend tree?

subtle vessel
#

yes

balmy pollen
#

without speed?

subtle vessel
#

what do you mean by speed?

balmy pollen
#

sorry

#

i get now

#

was thinking like when you are using a rigidbody

#

and you press left or right and its increase de value of x or y

subtle vessel
#

oh, no, this is blending between 9 different animation clips depending on the values of AttackX and AttackY

#

which you set using anim.SetFloat("AttackX", ...);

#

and AttackY

balmy pollen
subtle vessel
#

yes, that is what anim.SetFloat does

balmy pollen
#

ok, ok

#

but you think i can compare it with angles

#

like

#

if(mouseclick) {if(angle == 45 < angle == 90) { anim.SetFloat("AttackX", -1) }}

subtle vessel
#

you could do that if you want

#

or you could use sin/cos to find the actual x/y value of your position

#

and set those into the blend tree

#

and it will still choose the right animation, even if you're not passing in 1/0/-1 exactly

balmy pollen
#

i can add you in my friend list?

#

cuz i'll test this code now

#

and if i have some issue, maybe you can help

#

?

subtle vessel
#

you're welcome to continue asking questions here. I try to only help publically so that other people can learn from it too.

balmy pollen
#

no problem, but i'll @ you

#

tyvm for your help

desert lotus
#

how can I make this an endless vertical level, so that platforms infinitely keep generating the same distance apart, along with the walls keep going up

scenic nacelle
#

Can someone help me please I can't find the error in my jump code // MD

warm pebble
#

i dont know why but the speed of my enemy sprite is like doubled

#

im using git to work on a project from two devices

#

and on one of them the speed is good, while on the other its completely different

#

i dont understand why

late viper
warm pebble
#

correct i am just figured that out

#

how can i fix that?

#

i used the speed of the object times time.deltatime which caused the speed to be completely different on both devices

late viper
#

deltaTime fixes that, not causes it, so its probably something else

warm pebble
#

im trying time.fixeddeltaTime to see if that does something

#

was not that

#

i dont know what else it could be if all of the files are exactly the same

#
using System.Collections.Generic;
using UnityEngine;

public class Enemy_Movement : MonoBehaviour
{
    public Transform Player;
    public Transform Enemy;
    public float distance;
    public float moveSpeed;
    public Animator animator;
    public float direction;
    public Vector2 coordinate;
    public float angle;
    public bool visible;
    
    void Update()
    { 
        distance = Vector2.Distance(Enemy.position, Player.position); //Distance between player and enemy
        if(distance <= 10){
        visible = true; //Player is visible
        animator.SetBool("Visible", visible);
        }
        if(visible == true){
        coordinate = -Player.position + Enemy.position; //Coordinate for angle equation
        angle = Mathf.Atan2(coordinate.y, coordinate.x); //Find angle to determine animation for enemy
        animator.SetFloat("Angle", angle);
        if(coordinate.x >= -2 && coordinate.x <= 2 && coordinate.y >= 1){
            direction = 4; //Down
        }
        if(coordinate.x >= -2 && coordinate.x <= 2 && coordinate.y <= -1){
            direction = 2; //Up
        }
        if(coordinate.y >= -2 && coordinate.y <= 2 && coordinate.x >= 1){
            direction = 3; //Left
        }
        if(coordinate.y >= -2 && coordinate.y <= 2 && coordinate.x <= -1){
            direction = 1; //Right
        }
        Enemy.position = Vector2.MoveTowards(Enemy.position, Player.position, moveSpeed*Time.DeltaTime); //Go towards player
        animator.SetFloat("Direction", direction);
        }
        if(distance > 10){ //If Player is too far
            visible = false;
            animator.SetBool("Visible", visible);
        }
    
}
}```
#

this is the enemy movement code

#

nvm for some reason its deciding to work now

#

maybe i had time delta time wrong or somethin

craggy kite
still tendon
#

Hello, can someone help w making a 2d game? And no i cant just watch a tutorial bc my english isnt that good like in the tutorials.

craggy kite
#

What language do you need, I am sure there are tutorials in your language too

pseudo wave
#

Hello, i was making an inventory system, now working on the pickup of items and since i want to make a big project i wanted to know if it was more efficient to put the OnTriggerEnter2D on my player or on each item. If i put it on the player i would have to make many collision detections inside my player depending on the tag of the item, but if i put it on each item it would only need to detect tag "player"
so would it be more efficient to have many tag detection on only my player or have only 1 detection of tag "player" for many items in the world?

still tendon
#

Would be call if someone could help me in a talk or something

craggy kite
#

Got no time for that sorry, but I guess there are some germans here, maybe someone. But you are expecting a private teach lession for free, so do not expect too much too soon ๐Ÿ˜‰

still tendon
#

Ye your right. I watched some unity tutorials now and i think im kinda getting in to it

craggy kite
#

Its not that hard to start with, just take your time, do not skip even if it looks/sounds boring/easy

still tendon
#

If there is something like position... > 5f. What is this 5f? Does it has something to do with math?

craggy kite
#

5float

#

so unity knows its not an integer and does not round it for example

still tendon
#

Oh okay thanks

manic ruin
#

guys can some one tell me how can i call an "if" in void update just one time?

#

nvm ig

hasty adder
#

I am attempting to make the raycasts go towards two invisible points (DashLeft and DashRight) which to either side of the character on the same Y co-ordinate, however the raycast appear to be aiming in the complete wrong direction. Any idea of why this may be?

snow willow
#

Make sure that thing says "Pivot" instead of "Center"

#

and then double check the positions of your objects

hasty adder
snow willow
#

are they children of the player?

#

Oh wait duh I know the problem @hasty adder

#

you're not using DrawRay correctly

#

you're using it like DrawLine

#

switch to DrawLine

#

DrawRay expects a position and a direction. You're giving it two positions

#

Two positions is what DrawLine expects

hasty adder
ripe wind
#

I'm making a top down 2d game, and I'm on to character movement. Theres going to be some physiccs in the game, so should I use a rigidbody for movement, or a character controller?

hallow stump
#

isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x, transform.position.y - 2.2f), new Vector2(transform.position.x -+1.2f, transform.position.y), groundLayer);

#

new Vector2(transform.position.x -+1.2f, transform.position.y), groundLayer);

#

i'm trying to get the overlap to work on anything in between. Transform.position.x - 1.2f and Transform.position.x + 1.2f. isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x - 1.2f, transform.position.y - 2.2f), new Vector2(transform.position.x + 1.2f, transform.position.y), groundLayer); this works but doesnt feel proper

modest cargo
tacit wave
#

Alright I need final answers about character movement, it's getting me crazy.
I've been told earlier that I shouldn't make my character jump with AddForce, but use ForceMode.Impulse instead, which drove me to doubt about my whole code, did I use the right method for my movement, my jump, everything.

So, can someone at least a bit experienced and who knows the differences and uses tell me the best way (for a 2D platformer mechanically close to Celeste or Super Meat Boy) to:

  • Move left/right (velocity, AddForce, transform, anything else?)
  • Jump (velocity, AddForce, ForceMode.Impulse, anything else?)
  • Dash (No idea, anything?)

Can you also explain why to use a specific method, and not the other, just so it's clear in my brain that this method is the best and that I'll use it for the next months of my game's development.

Thanks a lot in advance to the person(s) who'll answer.

snow willow
#

AddForce and ForceMode.Impulse are not different things

#

FoceMode.Impulse is used with AddForce

#

To get a full understanding here, you should realize that the only result of calling AddForce is that the velocity of the Rigidbody changes

#

you can get exactly the same effect as AddForce by setting velocity yourself with the correct math

#

The math that is used depends on which ForceMode is used in the AddForce call

#
Vector2 force = <something>;
// this:
rb.AddForce(force);
// IS EQUIVALENT TO:
rb.velocity += (force / rb.mass) * Time.fixedDeltaTime;

// and this:
rb.AddForce(force, ForceMode2D.Impulse);
// IS EQUIVALENT TO:
rb.velocity += force / rb.mass;
tacit wave
abstract olive
modest cargo
#

According to documentation ForceMode.Force uses mass*distance/time^2 as its unit, while ForceMode.Impulse uses mass*distance/time

#

So they do the same thing, but use different unit for the purpose of keeping things physically consistent if you're into that

#

But that's not relevant to unrealistic physics

light torrent
#

Hello
I'm creating a grind stone game where I'm trying to deform the shape of the sword as it collides with the grind stone.
The sword is 2D sprite, so I'm focusing on deforming the 2D sprite.

I tried to change the sword sprite mesh properties by accessing it's triangles,vertices & UV and adjusting these values(nulling them) then use the OverrideGeometry to let these changes effect the sprite but it didn't work

Is there a better/working way to do sword deformation?

Please tag me on reponse

storm coral
#

I use multiple tilemaps in my game, using rule tiles, but i would like the rule tiles to change according to all of the tilemaps, not just the one they are in. how would i achieve this?

snow willow
snow willow
light torrent
foggy orchid
#

So im not really sure where I should ask this question.. but i got a problem.. : how do I render a quad over 2d sprites?

pulsar igloo
#

Hi I want to change scene when my character hit a door but I made all the codes wich I found and its don't work. Do you have a solution?

turbid heart
#

break it down,

  1. how to detect when character hit door
  2. how to change scene
vague pawn
#

I want to move my player horizontally only. Is there a specific command I can use rather than using "Vector2"? because "Vector2" has both vertically and horizontally values

turbid heart
pulsar igloo
vague pawn
turbid heart
#

use vector2

#

although, i dont know how you're moving your player at the moment

#

but if the method you're using needs a vector2, that's how you can use it

storm coral
#

I use multiple tilemaps in my game, using rule tiles, but i would like the rule tiles to change according to all of the tilemaps, not just the one they are in. how would i achieve this?

golden kraken
#

I have an idea, but I don't know how to implement

the game has a side view where the player can create objects and move them. I would like to make it possible for the player to break the object if the force is large. As in reality

crimson shard
#

Anyone knows how to get this var?

#

I have tried a lot of variants, but no one of them work

viral quartz
#

rectTransform.sizeDelta.y should do ?

crimson shard
#

Already tried this. This returns 0

viral quartz
#

hmm, let me try on my unity

#

Debug.Log("height: " + blackScreenImg.rectTransform.sizeDelta.y);

I got 1080 as my output, seems to work.

crimson shard
#

Strange. Maybe some sort of my mistake. Let me check it on another project

turbid heart
viral quartz
#

I tested on an image which is direct child of a canvas. Try with that and see if you get a different result?

viral quartz
crimson shard
viral quartz
#

what are the height and width of the parent of the rectTransform that you were trying to measure?

turbid heart
turbid heart
#

I changed the link. Try to google around

#

I donโ€™t know the solution, but i guess thatโ€™s the problem

crimson shard
#

Yep, that works. My thanks

turbid heart
crimson shard
#

this.GetComponent<RectTransform>().rect.height

#

Not the best solution, but it easy to optimise I think

digital kettle
#

In regards creating a new image in the game when clicking on something would it be Instantiate(Resources.Load("Images/imagename"), new Vector3(x, y), Quaternion.identiy); ?

subtle vessel
#

I'd try something like...

#
go.transform.position = new Vector3(x,y,z);
SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
sr.sprite = Resources.Load("Images/imagename");```
#

assuming the image is a texture, not a prefab of some sort

distant pecan
#

also using resources is pretty bad in performance and if you can it should be avoided

green anchor
#

how can i stop one-sided wall jump?

#

i think i must add addforce but it seems it doesnt work.

#

or i couldnt make it

solar oyster
#

someone pls help me with the rigidbody2d, my character wont stay facing forward but it will rotate when i hit objects, if its confusing dm me and i can screenshare. thanks in advance!

compact knoll
solar oyster
#

@compact knoll tysm, also how do i get this taskbar (idk the name) back in unity? i deleted it on accident lol im quite new

#

the one on the left with all the sprites

#

nvm i got it

#

its the hierachy

wide ginkgo
solar oyster
#

ty

buoyant olive
#

is there a way to get mouse position when your camera is on perspective mode?

tall current
#

Like - the mouse might be (from the camera's perspective) hovering over a point.

#

If you want that point. Then just raycast from the camera.

snow willow
#

depending on if you want the mouse position where it's touching an object or where it's intersecting a plane

pseudo turret
#

hello! I have a quick question if I may ๐Ÿ˜„ How would I make it so the "Game object" is only shown in the mask (like Sprite Renderer. show inside mask thingie :D) sorry second day of Unity don't know anything!

green wedge
#

Guys, im trying to add pushback to enemies hit, but unity is asking me for a "Y" component. Shouldnt substracting two vectors already produce another vector?

snow willow
#

the subtraction produces a vector, as you surmised

white cedar
#

this is my Knockback, but I can't make the player knockback in the oposite direction that he was hitted, without using ifs

snow willow
#
  • you definitely want a yield return null inside the while loop, or the whole loop will happen in a single frame
#
  • You're using transform.position.y as the z component of the force you're adding? What's the idea there?
#
  • you'ree adding kockbackForceUp to knockbackVecetor.y instead of multiplying, which seems incorrect
#

not sure what you mean about using ifs

white cedar
snow willow
#

if that's all you need, there's no need for a coroutine

white cedar
#

like this (?)

snow willow
#

use the collision normal

#

the code you shared is for adding the force, where's the code for processing the collision?

digital kettle
#

Would anyone be able to help me with this display issue? For some reason even if I manipulate the hierarchy I cannot get the images to layer correctly. It's always the last one on top. I've tried creating new layers and assigning them but the same issue occurs

paper timber
#

Question: can I fetch the final baked texture from a Sprite Shape?

#

I'm doing a drop shadow effect, so I'm looking to access the texture it produces at runtime

tacit iron
#

how do I lock a child's rotation on the x axis

snow willow
#

You could try something like:

transform.localRotation = Quaternion.Inverse(transform.parent.localRotation);
still prawn
#

is there a way to copy a tilemap with tiles to a different tilemap through code?

still prawn
#

aight nvm, just found my answer :p

paper sky
#

Hey so I'm coming over from a couple months of Gamemaker and thought I'd try Unity for some 2D stuff. When it comes to animating 2D art how is it usually done? In Gamemaker you have a different aniated sprite you switch to. Is that the case here?

late viper
paper sky
late viper
#

yes

paper sky
#

Ahhh ok cool

#

Thanks!

buoyant olive
minor barn
#

Horizontal Layout Group is so crude that it's practically worthless. I would be done now if I just manually arranged things.

atomic pond
#

how do i sync 2d objects in a multiplayer game? im using photon pun,
any ideas?

snow willow
#

follow the photon tutorials and examples

atomic pond
mossy canyon
#

I understand how to animate a 2d character (putting a set of sprites in an animator etc). But how does this work if the character is a ragdoll/multiple sections, where I can i.e replace the head to represent a different character type etc? Do I have to create an animator for every possible scenario ?

subtle vessel
mossy canyon
#

@subtle vessel Ok - not 100% sure I understood the distinction here, but I'll give it a go and see where it takes me ๐Ÿ™‚

subtle vessel
# mossy canyon <@!365978470267748392> Ok - not 100% sure I understood the distinction here, but...

Animation clips in Unity are collections of changes to gameobjects. Those changes can be changing position/rotation/scale of the transform, or it can be changing properties on other components. When you drag a spritesheet into the scene and automatically make an animation clip, the only property changing in that clip is the sprite on the sprite renderer. But let's say you have a base head sprite and a hair sprite on a child object. You could have an animation clip that changes the sprite on the face (to blink, say) and also moves the hair sprite. As long as the clip doesn't change the hair sprite (only moves it), you can have different objects that replace the hair sprite without causing problems in the animation

#

You could have one object with blonde hair and another with brown and the hair in both would move with the animation

mossy canyon
#

@subtle vessel Ok, I think that makes sense. I'll give it a go and come back to haunt you for sure! ๐Ÿ˜›

#

@subtle vessel For what I am trying to do, I pretty much need to scrap the spritesheet animation thing, and try setting up my own animations, where I just move different parts (sprites) around and/or resize them etc.. right ?

subtle vessel
mossy canyon
#

@subtle vessel Yeah, sorry for being vague. I don't really know what I am trying to do myself. I'm picturing in my head what I want to do, but I'm obviously setting the bar way to high for my current experience level,hehe ๐Ÿ™‚ Keep learning bits and pieces though, so I think it has value.

mossy canyon
#

@subtle vessel This looks pretty close to something I could do, https://www.youtube.com/watch?v=eXIuizGzY2A . So taking this tutorial into consideration, and your comments above, does that mean I can replace the sprite and bones will remain .. ?

Wanna learn how to make your characters come alive? Then Skeletal Animation is for you!

This video is sponsored by Unity.

You need to use Unity 2018.3 or later to use these tools.

Unity is hosting a 2D Challenge - Check it out: https://ole.unity.com/2dchallenge

โ— Rigging documentation: https://bit.ly/2S1Xn04
โ— IK documentation: https://bit.l...

โ–ถ Play video
split portal
#

Hi. I want to do some kind of 2d Raycast from the player position. it needs to be 0.5 by 0.5. WHich kind of raycast should I do?

noble rapids
#

i'm guessing you want Physics2D.Raycast with a layermask so you don't hit the player

karmic storm
#

Hey I have a huge problem. I've created a 2D character with a dust particle system while running. Everything worked fine until I wrote a line for the character flip. After changing the angle from 0 to 180 (flipping the character to the left) the particle wont show up anymore. Has anyone a guess why this is happening?

split portal
karmic storm
#

Hmm let me try it out

tough fractal
#

Hello, I'm new to unity and i'm trying to create a 2D platformer. I saw a useful package nammed 2d extras so I tried to install it but I keep getting this error. I have git, I added a path to git, I put the folder with the right name in the Package folder and I added the depedency in the manifest.json. I'm using Unity 2020.3 and I downloaded the 2020.3 branch (@ me pls)

Edit : for the ones who have the same problem, modify the link in the manifest.json, change #master to the name of your branch. for me #2020.3
And avoid to use the main branch

mossy canyon
#

I am instantiating a GameObject, that contains a sprite. I have defined the outline in the sprite, using the sprite editor. Can I then just add some collider and this will be automatically generated/added ? If so, which collider should I use ?

covert whale
#

i don't know if u can add a component during runtime i think u should just add it to a prefab and instantiate from that

mossy canyon
#

@covert whale I was using edge collider, and that seems to work .. if I changed to box, it doesn't seem so .. ๐Ÿคทโ€โ™‚๏ธ

covert whale
#

boxcollider or boxcollider2d?

mossy canyon
#

I added a boxcollider2d.. maybe I should drop the rigidbody, and only use the boxcollider ?

covert whale
#

i think u should keep the rigidbody

#

if an edge collider worked for u then i don't see any reason to change it to a box collider

mossy canyon
#

cant mix boxcollider with rigidbody, afaik

#

OK, cool ๐Ÿ™‚

covert whale
mossy canyon
#

Yeah, it seems to be somewhat working .. just need to detect collisions now, so I can start doing actions

covert whale
#

boxcollider2d with rigidbody2d

mossy canyon
#

Yes, the 2d ones you use together

covert whale
mossy canyon
#

Damn - new element to learn! ๐Ÿ˜› I jumped the gun on edge collider working btw.. seems to be making a straight line through the sprite. ๐Ÿ˜›

covert whale
#

yeah idk if edge colliders automatically work with sprite outlines

#

i know boxcolliders do

#

if u want to use edge colliders then u can add it to an object before hand and change the edges manually then instantiate from that object

mossy canyon
#

If I add the box collider 2d, it seems to add a square in the middle of the sprite - not following the physics outline

arctic cloud
#

Hi, guys. Does anyone know, how to change detection range in A*, if anybody uses it

covert whale
mossy canyon
#

See the little green square in the middle of the sprite?

#

@covert whale I have a sprite, where I added the outline. Then I have a prefab, where I load this sprite and instantiate it during runtime. I.e I generate these characters

covert whale
#

oh ok

#

in the prefab u can click edit collider on the box collider component and manually change the collider to fit

mossy canyon
#

@covert whale this is a general prefab though, that loads its own sprite based on a few criteria. I might be stupid here, but does physics shapes not follow the sprite ?

covert whale
#

sometimes it doesn't

#

in the sprite editor i think u have to generate a physics outline

mossy canyon
#

@covert whale yes, that's what I have done. And I was then hoping the outline would follow the sprite, so whenever I load it in one of my prefabs, the physics will be automatically applied

#

@covert whale This is the outline that has been generated for the sprite

covert whale
#

oh

#

i think the problem here is that i thought the custom physics shape was just a box but it's a polygon

#

try adding a polygon collider instead

mossy canyon
#

Polygon definitely surrounds the character, but it's waaaay bigger than the char ๐Ÿ˜›

covert whale
#

yeah i don't think it follows the outline of the sprite if u add instantiate it like that

#

after u instantiate u can set the shape of the outline using code i think

karmic storm
#

Does anyone know how to rotate parent without affecting child?

covert whale
mossy canyon
#

@covert whale would it be better if I created individual prefabs for all my character types ?

covert whale
#

how many do u have

mossy canyon
#

At the moment, just the one. But I would like to make this as dynamic as possible, so I can expand and add loads of different character types in the future

split portal
#

why does this not work? script is on a child of player. Collision matrix is set up as far as i can see. The objects it is interacting with are triggers. trigger query thing is checked

mossy canyon
#

This is more learning than anything for me though. I have no clue what I am doing ๐Ÿ˜„

covert whale
#

oh wait sorry not box

#

polygon

mossy canyon
#

Ah, right - let me try

#

Same result

covert whale
#

damn

#

i think u may need to have separate prefabs then

mossy canyon
#

Polygon appears same size as when added to the prefab

#

Not the end of the world, I guess. All characters will have different functions, so it'll be OK to split them into separate prefabs ๐Ÿ™‚

covert whale
#

alright

mossy canyon
#

@covert whale Works when I have isolated prefabs. Both ๐Ÿ™‚ and ๐Ÿ˜ฆ

#

Looks like the colliders have added a pretty significant performance hit though. Do I need one of these composite thingys to make it more effective ?

covert whale
#

composite colliders i don't think help with performance if u only have one collider on an object

#

if u want to improve performance then simplifying the outline and not having as many points helps

#

usually i use box or capsule colliders as they are enough to have the rough outline of the character while not slowing things down

mossy canyon
#

Alright, fair enough ๐Ÿ˜„ Thanks a bunch for your time, help and advice! ๐Ÿ™‚

#

Last question .. do I need to do anything special to catch collisions now? Ive added an oncollisionenter to my script, but it doesn't seem to fire, despite the characters actually colliding with other objects

turbid heart
#

also check OnCollisionEnter docs. You need to set up your objects in a specific way

mossy canyon
#

Collision detected in warrior!
Im an idiot ๐Ÿ™‚

#

Thank you very much! Was as simple as using the 2d version, instead of the 3d one ๐Ÿคฆโ€โ™‚๏ธ

shadow zodiac
#

i have a question

#

how can i convert a negative number to a positive number?

#

and vice versa

turbid heart
oak rapids
#

^

#

easiest way

#

you also have this cursed way

#
num = num - num * 2
#

it works

#

but who would do that

woeful sentinel
oak rapids
#

yes i know

#

if num were to be 2

#

it would be

proud monolith
#

ok

oak rapids
#

num = 2 - 2*2

#

which would be -2 bc bodmas

mossy canyon
#

@covert whale Got it working quite nicely now ๐Ÿ™‚

#

@covert whale my programatically instantiated characters now traverse the map on random, and upon colliding with a tree, they stop their random movement and proceed chopping it down! haha

covert whale
#

nice

sand lion
#

hi guys, im a bit new to unity. i updated to urp and 2d renderer for the lighting options. but im having troubles and seeing its experimental im not sure about this direction and i want to change it early in. so my question is three fold. 1. what is the best render pipeline or set up for a straight up 2d platformer. 2. can i go back to the standard renderer and how do i go about it (changing materials?) thanks in advance. also, nr 3. what lighting alternative is recommended, im looking at 2ddl and some others but its hard tonsay which is the most usable. i want it to be reliable and easy to use. i also really want shadows, so i dont have to bake them all by hand.

distant pecan
#

if all you want is some shadows URP with 2D renderer works perfectly fine for me, all you gotta do is add a shadow caster to the objects you want to cast shadow

prisma ocean
#

I'm trying to make spaceship movement. I know how to make acceleration + rotation, but I want to make it so that there is no drag. So if I accelerate to 5 km/h, then it stays at that speed. Setting the gravity to 0 in vertical input solves this, however as soon as I press the down arrow to decelerate, it instantly goes to accelerating backwards instead of gradually decelerating and then going backwards.

#

how would I fix this? ๐Ÿ˜ฎ

#

thanks

vague pawn
#

I put walls in my 2D game with box collider and still when I move my player to collide with them he is still moving through them like there is no any collider at all. My player has both Rigidbody2D and box collider also. Can someone please help me with this? because my player box collider works just fine with another object, but with my walls it's failing to work.

turbid heart
snow willow
#

Kinematic rigidbodies are unstoppable forces

vague pawn
digital kettle
#

Just a quick question guys, in what scenario would you use image over sprite? Sprite gives you the ability to layer things much easier while image doesn't seem to be as good?

late viper
digital kettle
#

Gotcha so sprites for gameplay and image is for UI at the forefront

snow willow
#

Just to further clarify the terminology:
A Sprite in Unity is an asset. It's (almost) the raw image itself (it can be a small slice of the image, plus a pivot point). A SpriteRenderer and the UI Image component both use Sprite assets as the "thing" that they display. An Image is just a UI component in screen space, and a SpriteRenderer displays a sprite in the game world on a flat mesh.

green peak
#

hello! i tried making a dialogue choice system, and i ran into a problem ๐Ÿ˜…
i tried placing some symbol a bit to the left of the selected text, like this:

#

i tried using the following code:

//YingYang is Image
//text is TextMeshProUGUI
YingYang.transform.localPosition = text.transform.localPosition - new Vector3(text.textBounds.size.x + YingYang.rectTransform.rect.size.x, 0);
#

the problem is, the longer the string becomes, the further that ying yang moves

#

i know that the textBounds.size increases, but im not sure why does this big offset occur.. ๐Ÿ˜…

snow willow
green peak
#

so like, the anchors?

snow willow
#

Familiarize yourself with this and everything will fall into place

#

yes, the anchors, pivots, etc..

#

Make sure you are using the correct settings on the Text object as well

green peak
#

but is it possible to make the anchor relative to some object?
because i have like
5 separate texts ๐Ÿ˜…

snow willow
#

e.g. it should be left-aligned if you want it to stick to the left side

green peak
#

so if i understand correctly, i should use a vertical layer group here..?

#

hm..

#

how would i place the symbol next to the text though?
it seems like it just stacks them

solar thicket
digital kettle
#

Is there a way to outline sprites? The outline component doesn't seem to work when I adjust it

keen lava
#

Hello Folks!

#

I have a VERY weird issue

#

in a build on every platform (Ps4, PC, Switch etc)

#

We have a set of 2D sprites that are the characters in a battle, all animations work fine AS LONG as they are not in a timeline (we use these for in game cinematics), when the animations are looping inside a timeline, they flicker right at the end, as if there were some missing sprites, could there be a reason for this? My gut is telling me it's an asset bundle issue, because it's impossible to reproduce on the editor, but 100% reproducible on builds, but am not discarding anything!

#

BTW I would love to show a video of the issue but we can't because the game is still under nda ๐Ÿ˜ฆ , but we have a deadline soon and I would love ANY pointers here

agile snow
#

Is there any way I can detect the most right tile on the map?ใ€ฐ๏ธ

abstract olive
keen lava
#

@abstract olive that's the thing, they are supposed to loop, but instead of looping seamlessly (as they do during regular gameplay) they flickering right at the end

#

as if they were missing a sprite

abstract olive
#

What if you reduce the clip in the timeline by a frame, just to test.

#

Just pull the end back a bit.

keen lava
#

huh, I could try that,the weird part is why is it happening on builds only and never on the editor

#

:/

buoyant olive
#

what function do you use to detect mouse hover on top of a sprite

buoyant olive
#

oh okay

#

thanks

elder minnow
#

You could do it in other ways, but this is the simplest.

#

Alternatively you could have a list of sprites in the scene / room / menu or whatever and iterate through them each time the mouse moves and calculate whether the mouse position intersects with the sprites boundaries.

buoyant olive
#

does OnMouseOver accept any params?

craggy kite
#

Short, nope, it does not

buoyant olive
#

shet

vocal condor
#

What did you need it to know?

buoyant olive
#

aw naw its fine now got a way around it

#

also is it possible to make a panel follow a gameobject?

#

no wait,

#

is it possible for panel to follow the mouse?

#

cuz it dont translate well

#

the position i mean

vocal condor
#

Panel? Are your referring to UI Panel?

buoyant olive
#

yes

vocal condor
buoyant olive
#

well, i tried using world.screenpoint to ray

#

but that only works for my gameobjects so idk how else

compact holly
#

    // Start is called before the first frame update
    void Start()
    {
        Transform origPos = originPoint.GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        fTicks += Time.deltaTime;

        Vector2 origPos = new Vector2(origPos.x, origPos.y);```
How can I simply get the transform position of the GO that I have?
turbid heart
#

for future reference, you dont need to GetComponent<Transform>, all GameObjects already have their transform cached. just use transform

compact holly
#

maybe I'm wrong with my question, I just want to know how I can assign the GO's transform position to a new vector2 variable

turbid heart
#

well, do you know how to assign a position?

#

and do you know how to declare a new Vector2?

compact holly
#

yes

turbid heart
#

and just so you know, assigning your position to a variable only assigns the position at the time

compact holly
#

or am I doing it wrong

turbid heart
#

it doesnt automatically update

#

what you're doing now

Vector2 origPos = new Vector2(origPos.x, origPos.y);

is actually assigning the x and y of origPos, to origPos

#

you havent even told origPos what it is, and you're assigning it to itself? hence the error saying you're probably using something unassigned

#

you might want to take a step back, and explain what you're trying to achieve here?

turbid heart
#

and in case you're unaware, you've already done it at least twice

compact holly
#

ohh yeah, I forgot to rename it, mb

radiant junco
#

i didnt know where to ask this but my jump animation has a problem where it only plays when i click space mid air

#

nvm i figured out that the spacebar need active input to play the animation

#

but i dont know how to make it so if i click spacebar once the animation plays

tepid vector
snow willow
#

might give some hint as to what setting(s) you need to tweak

tepid vector
#

according to the profiler the method thats causing it is Canvas.SendWillRenderCanvases. i searched it and there was a couple solutions but they were for a generic problem i couldn't find an answer as to why specifically TMP is so much slower

snow willow
#

If you turn on deep profiling you might get something more specific

tepid vector
#

didn't have that turned on. that offers abit more insight, thanks. will have a search of the more specific causes

dreamy crane
#

anyone have any recommendations for placing objects along a mesh at regular intervals? I have a randomly generated 2D mesh that I want to place 'landing zones' on for the player to constantly travel between, but struggling to wrap my head around the math to do it properly

#

overall mesh looks like this

#

curious if it's even worth trying to do programatically or just manually place them since the mesh is static

snow willow
dreamy crane
#

is there an elegant way to do that knowing the 'in view' portion of the ground? essentially i'm trying to create a clone of the functionality in 'desert golfing' where the player lands, and the camera transitions to the next 'chunk' with the landing pad at the other end of the screen

snow willow
#

I don't understand

dreamy crane
#

Basically this functionality

dusky wagon
#

Is there a way to change what tiles the rule tile counts when looking for what tiles are next to it?

#

I want it to count all tiles that are from the same tile map, not just itself

still tendon
#

How do i make basic 2d player movement?

turbid heart
quartz breach
#

Just want the damn minigun to fire

#

Finding it very hard as all tutorials seem to skip important details

#

They're just like "So you click animation and I've already done that so you click play and it works"

modest cargo
arctic cloud
#

Hi, guys, I'm trying to make a script which moves an object to a camera position, but it returns "Object reference not set to an instance of an object." I think this is caused by a camera which follows player (because it works when the camera is stable), but I don't know how to fix it.

late viper
arctic cloud
#

No

#

I put it now

#

omg you are such a pro man thank you

prisma ocean
#

Er so I'm using rb.AddForce to move my spaceship, and then transform.rotate to well uh rotate. This is all fine except when I try rotating at high speeds, then it looks like the ship vibrates while rotating. is this because I have rotate in update rather than fixedUpdate?

subtle vessel
#

though even better (in my opinion) is to use the new input system to read input as events rather than in Update. In many cases you can get rid of your Update function completely

prisma ocean
#

new input system? ๐Ÿ˜ฎ

snow willow
#

If you're using a rigidbody, it's better to rotate your ship with rb.MoveRotation instead of rotating the transform

runic orbit
#

How can i fix that. text is from textmesh, i set value of z to-1 because on 0 text is under sprite.

subtle vessel
#

and are the hexagons part of the UI? Are they using an Image/RawImage component, or a SpriteRenderer?

runic orbit
#

hexagons and text is one object .
object move with diffrent speed and when objects go trough self, text rendering over all sprites

snow willow
#

so again - what is it? SpriteRenderer?

#

and TextMesh?

runic orbit
#

yes

#

hexagon is priterenderer and text is textmesh

snow willow
#

if you want things to show in front of or behind each other - they need to physically be in front or behind each other

#

since these are world space objects

white cedar
#

this shouldnt be giving me the length of the video?