#🖼️┃2d-tools

1 messages · Page 55 of 1

maiden forge
#

Also when you're using .GetKey you can do

 if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
#

Whats that thing they need to do so vs registers errors, its like formatting it or something? Because i think Quasar needs to do it

maiden forge
still tendon
#

ok i go

maiden forge
still tendon
#

I better do all the code from the beginning, I've been trying all day to program something that should be super easy

#

and already configure my vs code for unity

#

about two hours ago

late viper
#

pay attention to capital letters, {} and ; they're all important

still tendon
#

oki

#

i will try

still tendon
#

how do i make my 2d character dash?

true shadow
#

How could I achieve more efficient procedural 2D generation? For example Terraria large worlds are 16800x4800 and generate pretty fast

modest cargo
true shadow
modest cargo
#

Configure them using the generated data at runtime and load/unload them based on player's distance

#

When generating large maps, quadtree/octree optimization can be pretty important to keep the amount of data sane

true shadow
#

Also, do you think it could work by having one tilemap and using SetTile to add/remove tiles?

violet adder
#

if anyone needs to flip something like the transform of a gun barrel for shooting, i just got this working;

                        // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
                firePoint.transform.eulerAngles = new Vector3(
                    firePoint.transform.eulerAngles.x,
                    firePoint.transform.eulerAngles.y + 180,
                    firePoint.transform.eulerAngles.z
                );
            }
            // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
                firePoint.transform.eulerAngles = new Vector3(
                    firePoint.transform.eulerAngles.x,
                    firePoint.transform.eulerAngles.y - 180,
                    firePoint.transform.eulerAngles.z
                );
            }

and

    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
#

to actually get the gameobject (firepoint for me), do <name of game object> = GameObject.Find("<name of game object>"); in start/awake

#

this is for if you arent using brackey's player controller btw

honest python
#

is there any way I could remove a box that was drawn with Gizmos.DrawCube?

violet adder
#

nvm i got it

faint hollow
#

What it means?

violet adder
#

it means you didnt define GROUND_TAG

#

and why is your ground part of your background

modest cargo
digital dagger
#

I have already asked in the beginner code channel, but this channel should be more fitting. Anyways I just tried to get a simple top down firing going, but my bullet just wont fly off. It rests in the same place, it is instantiated.

digital dagger
torn chasm
#

and, if you want to use addforce, maybe have a position offset to the bullet when it shoots depending on the direction of fire

digital dagger
digital dagger
torn chasm
#

wait does the bullet disapear, or does it just stay in place?

digital dagger
#

It just stays in place

torn chasm
#

oh

digital dagger
#

Maybe it gets stuck at the player?

torn chasm
#

does the player have a solid, non-trigger, collider?

digital dagger
#

This is how it looks atm. Green dot is the player and pink triangle the enemy. Blue dot the projectile

digital dagger
coral tusk
#

Hey guys, I want to get a point in a direction based on the rotation of another object... I have no idea how to do it but I have been trying to use

        float rot = playerSprite.transform.rotation.z;
        rot = rot * Mathf.Deg2Rad;
        
        if (Mathf.Abs(h) > hDeadZone)   //If choosing to move
        {
            hSpeed = Mathf.Cos(rot);
            vSpeed = Mathf.Sin(rot);
        }
        
            Debug.DrawRay(transform.position, new Vector3(hSpeed*0.5f,vSpeed*0.5f,0),Color.red);
torn chasm
late viper
coral tusk
#

I want it to be, when I press left, my character moves a specified amount, in the left direction of the sprite, but not it's pwm object

#

ahhhh

#

thanks

digital dagger
coral tusk
#

oh jeez, thanks a heap @late viper

torn chasm
torn chasm
#

you want me to dm it to you?

digital dagger
#

Yes

sly vessel
#

Hey all, i have bullets in my scene which move by velocity. I want them to slow exponentially slow down over total range regardless of how long the range is. I've tried alot but cant figure it out.. Any ideas?

desert cargo
#

oh wait...

#

I see what you're doing.

#
var v = rb.velocity;
v.magnitude = Mathf.Lerp(maxVelocity, minVelocity, distance / range);
rb.velocity = v;
sly vessel
#

magnitude is read only

#

cant assign values to it

desert cargo
#
rb.velocity = rb.velocity.normalized * Mathf.Lerp(maxVelocity, minVelocity, distance / range);
sly vessel
#

oh wow

#

thats exactly what i need

#

thank you so much

hallow oak
#

Hey uhhm I´m currently working on my first 2D-Plattformer and wanted to ask if there is any way to make it so that the box collider of a Sprite always automatically matches the Texture of a sprite and not the size of the Sprite itself.

dusky wagon
#

How do I make a script that changes rule tiles to count anything that is one the same tilwmap as them as neighbors?

#

So that it doesnt just count itself as a neighbor, but also any other tile that has been placed on the tile map

dusky wagon
#

Does anyone know?

old zephyr
#

how can i apply my code to the y axis aswell?

#

ive been trying withn no succes

#

its an enemy mover script btw

lament spire
#
transform.right = aim - (Vector2)transform.position;

For some reason this modifies the x rotation when it's only supposed to change the z
(2D game)
Or if that's intended behavior how do I prevent it of doing that, I tried that:

Vector3 eulerRotation = transform.rotation.eulerAngles;
transform.rotation = 
Quaternion.Euler(0, eulerRotation.y, eulerRotation.z);
AND
transform.rotation = 
Quaternion.Euler
(0, transform.rotation.y, transform.rotation.z);

Both not working for different reasons
(First one does nothing and second one prevents z rotation)

hoary ginkgo
#

I need help, Been stuck for 2 days trying different ways to fix my issue. I have my two scripts below. one is my timer script and the other is my stat script. The code below my timer allows me to store my timer in a format that I turn into a string on my stat screen. So I have figured out how to store the longest run time but now I am trying to add up all run times and I cannot figure out how to add up the numbers. When I try adding them the numbers go above 60 for seconds an above 100 for milliseconds.

lament spire
snow willow
hoary ginkgo
#

What would be the math equation to convert that number to minutes, seconds, milliseconds?

hoary ginkgo
#

So I read through twice. Boy myhead hurts

hoary ginkgo
#

Thank you guys so much. I got it figured out, changing my original mess of a code for saving longest run time. The Link really helped the the advice about converting a single type of time like milliseconds save my rear end.

#

I am so close to finishing and publishing my first game. pretty excited. Maybe one or two people will actually download it lol

marsh pine
#

is there a way i can get my camera to smooth zoom and position on a game object, like in the game over screen in mini metro?

snow willow
#

but scripting it yourself is also not that hard.

supple breach
#

Hi guys, does anyone know any way i can save my information into a text file on webgl? i tried doing that but my game hangs after build

knotty barn
#

File IO should work fine on browsers, they generally just have their virtual filesystem.

kind stag
#

I know this is super simple, but I'm making a sort of Pong clone just for display, and I want all the elements to be the same pixel dimensions, just the area of play to be bigger, at all screen resolutions. How do I go about this?

craggy stone
#

I need help with something , and that something is that i need help with rotating sth

So ,

There is "Object A" and "The Player"

I want to make it so wherever i move my mouse on the camera , "Object A" orbits "The Player" with on a circle with a set radius .

Any way i can manage to do this?

kind stag
#

What is the mouse affecting?

craggy stone
#

Im basically trying to recreate the game rotmg if u know it .

I made a system where you can rotate the camera with Q and E

And you can move around with WASD obviously

Im making it so that i fire where i point my mouse at .

mental idol
#

At a set distance

craggy stone
#

yes

craggy stone
#

here is a brief explanation

#

that red thing is the object ,
that gray circle is the orbit path ,
that in the middle is the player .

craggy stone
#

Yeah but from what i get , Rotate ADDS rotation to the object while i want to directly SET the rotation

mental idol
#

Habla no ingles

snow willow
#

then in your script you just rotate the pivot and it works

hasty meteor
#

yo i want to add recoil for my game, i want to make it where you point a shotgun down and shoot, then it pushes you up in the air

#

not like anyone needs an explanation by what i mean but heres one

snow willow
hasty meteor
#

make a script for that?

snow willow
#

Probably would put it in your script that handles firing the fhotgun

hasty meteor
#

alr ill see

#

2 errors

snow willow
#

syntax rules of C# must, of course, be followed

hasty meteor
#

i dont know what anything of scripting means so idk what that means

snow willow
#

C# (the programming language you write Unity scripts in) has rules

#

your code isn't following those rules

#

and so it can't be run

hasty meteor
#

k

#

thanks though

craggy kite
#

your rotation is wrong because I guess your standard 0 rotation is messed up

#

I dont know, it looks like your camera is rotating, is that intended?

#

yeah, that rotates around 100, for whatever reason, so it is intended, yes?

#

YOu should know, what are you trying to rotate?

#

you are trying to rotate the player?

#

The camera is attached to the player, right?

#

Thats your issue, just make a smooth follow script for the camera, then you can just flip the player either with 180 or just localscale.x to -1 and 1

#

As long as your camera is attached to your player, it will rotate too and therefore look weird, look at your scene view while playing ,you will see your camera fly off

#

I wrote everything you need to know 😄 detach camera, make it follow the player with a script, in your flip code, use 180 for y rotation or just localScale.x to -1 or 1 depending on the direction

craggy stone
vale dock
#

does anyone happen to know of any videos or pages that have info on how to make a pokemon dialog system? or does anyone know code to accomplish that? i have a dialog system that pops up and shows the text, but what i am wanting also is how in pokemon, the letters popup 1 at a time as if its being typed, and then if its a long bit of dialog, the player can click to go to the next page of dialog

snow willow
#

Basically TextMeshPro gives you the maxVisibleCharacters property which will do what you want

vale dock
#

i found another script though im going to try

craggy kite
vale dock
#

ok so i got the slow revealing text working, but still not quite understanding the page system

faint hollow
#

The 'Vector3' is not working and idk why

snow willow
#

you're trying to assign playerposition.x, which is a float, to tempPos which is a Vector3

#

Also you need to get your VSCode configured properly so it shows those errors. You can find instructions in #854851968446365696

faint hollow
#

I already installed all the extensions and the .NET

snow willow
#

Did you do the rest of the steps?

tawdry knot
#

I've got an issue where my Sprite Renderer of a specific Game Object isn't responding at all to what I put in my Update Function, I'm just trying to enable and disable it at specified conditions, but it won't respond to anything
i tried to enable/disable it at the beginning and the end to make sure any other functions that are called in Update doesn't mess with it
I also looked at every keyword for "Sprite Renderer" in all my files to make sure it didn't change anything
Once I enable or disable the Sprite Renderer in the Unity Editor and press play, that'll be it's value for the rest of the game

I'm wondering what factors might lead to this problem? I do use Coroutines a lot, but only one of them disables the Sprite Renderer, and my problem is that whatever value I set it in the Unity Editor is what remains throughout the game
and I haven't used the Sprite Renderer Property in any of the Animations as well

#

I enable and disable it at the same time with my Polygon Collider for the Game Object, and the polygon collider enables it at the correct moment, but the Sprite Renderer doesn't change

#

TLDR: Game object in question is just a spear my boss holds, it's animated alongside the boss using sprites and transform, and I want to make it visible when their health is low
Collider is enabled at the correct moment, Sprite Renderer is not
Update() has no influence over Sprite Renderer, suspecting it has something to do with Animator, but checked that Sprite Renderer Enabled property isn't in any of them

#

Been trying to fix this since morning 😩 , if anyone knows anything about how Sprite Renderer might be enabled/disabled or how it's called please lmk

hollow stratus
#

For some reason, the built version of my game runs differently than the editor version of my game. Does anyone know why?

hollow stratus
tawdry knot
hollow stratus
#

can you show me the conditions and the code you are using to hide it?

tawdry knot
#

yea! Here it is in the start function to make sure it's off temporarily

#

here's the update function

#

It's enabled in !spearThrown, and when Phase 2 begins at else if ((health <= phase2))

hollow stratus
#

where are you changing the value of spearThrown

#

and where are you changing phase

tawdry knot
#

it's disabled when ThrowSpear is called, and spearThrown is set to True in a gameobject prefab while it still exists

#

phase is called in the update function and changes based on the health of the boss

#

they're both called at the right time when I put a debug log there

hollow stratus
#

ok I notice you do

spearHold.GetComponent<SpriteRenderer>().enabled = true; if phase is 1

but you don't do

spearHold.GetComponent<SpriteRenderer>().enabled = false; when phase is not 1

#

is this an oversight?

tawdry knot
#

spearHold works fine, spearTailHold is where the problem is at, mb it gets confusing with the names

#

I want the character to hold the spear in phase 1 with his hands, phase 2 and 3 he holds it with his tail

#

works fine with spearHold, not spearTailHold

hollow stratus
#

this isn't really a solution, but if you are calling GetComponent so much you should probably just set a reference before start

#

so you don't have to GetComponent everything you use spearhold or spearholdtail

tawdry knot
#

ohh right, ty for the tip

hollow stratus
#

what is spearhold and speartail?

#

just gameobjects?

tawdry knot
#

yep both are game objects

hollow stratus
#

why doesn't the setactive method work again?

tawdry knot
#

pretty much identical, aside from being animated differently and that spearTail has a collider

#

I'm not sure myself

hollow stratus
#

so you have 2 image essentially where one image he holds the spear in his hand and one in the tail right?

tawdry knot
#

They both have different Parents, and the parent of Tail Spear occasionally gets .setActive(false) if that has an influence

#

they're the same image just placed and animated differently

hollow stratus
#

and spearTailHold.SetActive(false) is what you tried?

#

and nothing happened?

hollow stratus
#

parent getting set to false doesn't affect their active status directly

#

i.e. when the parent is turned to false, everything underneath is false but they retain their true/false so that when the parent is back to true, the children will be what they were before the parent was turned off

#

but obviously something won't be active if the parent is not active if that's what you meant

tawdry knot
#

makes sense

hollow stratus
#

can I see the hiearchy of the part your issue is at?

#

like what are the parents/children of tailspearhold etc.

#

also I don't know if this is an option, but I would just switch everything to setactive instead of enable

tawdry knot
hollow stratus
#

but if that's not an option then it makes things harder

tawdry knot
#

sounds good, is there any coding benefits other than simplicity for that?

hollow stratus
#

I think it's just good practice

#

and there isn't really anything you can't do with setactive

#

can I see where you set SpearTailHold?

tawdry knot
#

like when i declared it?

hollow stratus
#

also if you have more than one sprite renderer that may be the issue

#

yes

#

honestly just change all your enables to setactives and see how it goes from there

tawdry knot
#
    public GameObject SlashPrefab;

    public Transform TopCenter;
    public Transform BottomCenter;
    public Transform BottomLeft;
    public Transform BottomRight;

    public Transform TailLocation;

    public GameObject SpearHold;
    public GameObject SpearTailHold;
    public GameObject Arm;
    public GameObject Claw;
    public GameObject Tail;
    public GameObject TailPoint;
    public GameObject SpearTailPoint;
    public GameObject Head;
    public GameObject MasklessHead;
    public GameObject Mask;
    public GameObject Red;
    public static bool FightBegun;
hollow stratus
#

does tailspear only have one spriterenderer?

tawdry knot
#

seems so

hollow stratus
#

if nothing's wrong with your code setactive should make your problem a lot easier to solve

#

but I think it might be with the code

tawdry knot
#

i'll give setative a try tomorrow

hollow stratus
#

if you want u can just dm me every place that is related to settailhold

#

every place of code

#

so I can track the problem down

tawdry knot
#

oo ok, i'll let you know then if I still haven't solved it until then

hollow stratus
#

kk

tawdry knot
#

thank you for helping!

kind stag
#

I'm actually using this for UI but I don't think this is really a UI question: I've brought in a 22x20 spritesheet and imported it as a sprite asset with all the slices in the right place etc. In code, what's the right class to use to load this up, see how many frames it has, access individual frames etc?

dusky wagon
#

How do you access the size of a collider? I have a reference to the collider but cant seem to find the right path to the size

rigid kindle
dusky wagon
#

Thank you, that seems to be the right thing, but how do I modify it?

Cannot modify the return value of 'Collider2D.bounds' because it is not a variable

I get this error when I try to assign a value to it

#

I tried

collider.bounds.size = ...;
rigid kindle
#

Is it possible to modify the values of bounds.min and bounds.max?

lean estuary
#

And you can only change .size/.center property on the default simple collider types.

dusky wagon
#

What are default simple collider types? I am doing it on a capsule collider

hollow crown
#

The bounds is generally derived from the shape properties

#

A capsule collider has height and radius

lean estuary
dusky wagon
#

Actually I think I fixed it

#

Instead of referencing a Collider2D I referenced a CapsuleCollider 2D and that does seem to have a size parameter

#

And does anyone know how I can modify what a rule tile counts as a neighbor?

#

I want it to count anything that is one the same tile map as the rule tile itself

kind stag
#

I've got a 20x22 sprite sheet that all looks fine in the inspector, and if I scroll through all the sprites under it, the animation is playing in the right order, BUT...

#
sourceRect = allSprites[frameIndex].rect;
frameIndex++;
frameIndex %= allSprites.Count;
#

Doing that, the frames seem to be playing in the wrong order. Is there an obvious thing I'm doing wrong?

kind stag
#

Looks like it's playing the rows in the wrong order, but the columns within that row in the right order. What?

lament spire
#

Hey, so I have this 2D animated character, and I would like to make color variants of it without re animating the same things with differents sprites for every variation

#

is there a work around ?

lament spire
#

Might not be your problem but it sounds like it

#

like x going left when bigger

kind stag
#

In the end I just decided to do this:

var assets = AssetDatabase.LoadAllAssetRepresentationsAtPath(SpritePath);
allSprites = assets.OfType<Sprite>()
    .OrderBy(s => s.rect.y)
    .ThenBy(s => s.rect.x)
    .ToList();```
#

then it's fine.

dusky wagon
# dusky wagon And does anyone know how I can modify what a rule tile counts as a neighbor?

I made a custom rule tile script and Im trying to achieve this but all that is inside the script by default is this:

    public bool customField;

    public class Neighbor : RuleTile.TilingRule.Neighbor {
        public const int Null = 3;
        public const int NotNull = 4;
    }

    public override bool RuleMatch(int neighbor, TileBase tile) {
        switch (neighbor) {
            case Neighbor.Null: return tile == null;
            case Neighbor.NotNull: return tile != null;
        }
        return base.RuleMatch(neighbor, tile);
    }
}```
And I only see the method where you can define when a rule match is true, but I dont see anything that can help defining what a neighbour is
forest badge
# dusky wagon I tried ``` collider.bounds.size = ...; ```

my code for the spriterenderer size is this
FightBottom.GetComponent<SpriteRenderer>().size = new Vector2(8, 1);
so first off it might be because you didn't put in the parenthesise at the end of bounds or maybe because you should've used a vector for it. it works for me, so if it doesn't for you, i'm sorry

dusky wagon
#

Thanks, but I already got it to work, it worked when I made the collider be a CapsuleCollider2D instead of a Collider2D

forest badge
#

oh

humble forge
#

I have diagonal wall sprites in my tileset, that i'm using transparency sort axis with. it works fine, however the diagonal walls cause some issues

#

because the sorting is based on y axis and they're diagonal, the player sprite can clip through them if they move close to the top part of the sprite

#

since it's diagonal, the character sprite goes higher in Y than the center of the wall sprite, and the character gets sorted under it automatically

#

how can i fix this?

lament spire
#

what perspective is your game

#

like top down ?

#

side scroller ?

humble forge
#

isometric, sorry should've mentioned that

#

pics for clarification, here its sorted correctly

#

and here it gets sorted under, because it moved diagonally along the wall to a higher Y position

lament spire
#

will the player sometimes be behind said wall ?

humble forge
#

yes

lament spire
#

maybe just put the center of the player at it's feet

#

that way his position is calculated from that

humble forge
#

it is already

#

actually nevermind, I don't think it is

#

i'll try that

#

how can i change all the pivot points of sprites of a sliced spritesheet at once

humble forge
#

so, that didn't work, the position is apparently not calculated from the sprite's pivot point but the center

#

which is stupid in my opinion, btw

#

apparently unity WAS smart enough to think of that :)

abstract gulch
#

I am trying to make a UI button spawn randomly

Vector3 randompos = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), 0);
            Debug.Log(randompos.x);
            GameObject instance = Instantiate(targetPrefab);
            instance.transform.SetParent(canvas.transform);
            instance.transform.position = randompos;
            instance.SetActive(true);

The debug log logs for example 86 but the real position of the button is -883. Anyone know why this might happen?

turbid heart
unborn sundial
#

When I resize the box around a TMP Text object by hand, what is being modified? The RectTransform's width and height aren't changing at all. (But if I change them manually, the box does resize, but only a little. There doesn't seem to be a logical connection)

snow willow
#

unless it's the yellow box

#

in which case that's the margins

unborn sundial
#

yes its a yellow box

snow willow
#

which you can find buried in other settings or something

#

yeah it's the margins - that tripped me up a bit recently too

unborn sundial
#

hm ok, I'll look them up

snow willow
#

And no don't ask me exactly what those do because I don't know 😛

unborn sundial
#

heh. this RectTransform / TMP stuff seems needlessly complicated

#

oh I see.. there's a yellow box and a white box.

#

the white box is the width/height and the yellow box is the margins relative to it

#

they overlap perfectly if margins are set to 0,0,0,0

snow willow
#

yes

fierce gull
#

if im making a 2d player gameobject, do i put the hitbox as the external component and put the sprite as a child of it or the other way around?

snow willow
#

I usually do someething like this:

Player (main scripts, Rigidbody2D)
  Visuals (empty, can be rotated to rotate whole player)
    Collider (Collider2D)
    Sprite (SpriteRenderer)
  Other stuff
fierce gull
#

parent component

jagged canopy
#

Anyone has any tips on how to make a good stickman ragdoll which moves using physics?

stable marlin
#

hi this is a sprite with some particle system on it, can i make the particles sorted so the particle that is on his foot render in front of him and the others above the legs behind it? or should i make 2 different particle systems just for this?

misty kelp
#

I would like a script for boiling a lobster in a 2D game.

obsidian finch
fringe path
#

perfection

misty kelp
compact knoll
#

nah nah nah, that's not scalable. You need to do lobster2D.SetState(State.BOIL)

obsidian finch
fringe path
#
if (lobster.isAlive) {
  lobster.stepBoil();
} else {
  person.eat(lobster);
}

kappasip

obsidian finch
fringe path
misty kelp
#

I want to make recipes.

late viper
misty kelp
#

I want to make a game similar to Cooking Mama, but not exactly like it.

abstract olive
#

What is your actual question, making minigames like cooking mama is a whole set of various actions. You need to decide on what you're going to actually make.

worthy delta
#

public Input Controllerleft = Input.GetAxis("Left Analog Stick (Horizontal)");
Could someone help me figure this out I want to add controller support but no clue how

snow willow
#

not sure what you're trying to do with that Input field situation. Doesn't work that way

worthy delta
snow willow
#

If you use GetAxis you have to have the axis defined in Project Seettings -> Input Manager

#

Do you have Left Analog Stick (Horizontal) defined in the Input Manager?

#

And again - you just read the value as a float, it doesn't return an Input object

#

and either way, that call needs to happen inside a method, not floating somewhere not in a method

worthy delta
snow willow
dusky fable
#

@snow willow Hey you probably don't remember me, but 4 days ago you helped me realize that I was feeding a position vector into a slot that needed a direction vector and I wanted to thank you.

dapper stump
#
 {
     print("hi");
     // force is how forcefully we will push the player away from the enemy.
     float force = 50;
 
     // If the object we hit is the enemy
     if (c.gameObject.tag == "enemy")
     {
         // Calculate Angle Between the collision point and the player
        ** Vector2 dir = c.contacts[0].point - transform.position;**
         // We then get the opposite (-Vector3) and normalize it
         dir = -dir.normalized;
         // And finally we add force in the direction of dir and multiply it by force. 
         // This will push back the player
         GetComponent<Rigidbody2D>().AddForce(dir*force);
     }
 }```
I'm trying to move and object the opposite directions of what another object collided with it at. I got a error on what was bolded. I copy pasted the code from another website btw.
snow willow
#
Vector2 dir = c.contacts[0].point - (Vector2)transform.position;```
misty kelp
#

C'mon please help me make a similar game to Cooking Mama?

woeful sentinel
misty kelp
late viper
late viper
#

No.

misty kelp
#

Be nice.

late viper
#

It's not me being not nice, its literally impossible for me or anyone else to do that

#

You need to decide what you specifically want in your game, and build it bit by bit. No one here can do that other than you

alpine swan
#

Go on fiverr someone might do it for 10$ xD

olive magnet
#

I'll do it for $20

late viper
#

Damn, have some standards people

olive magnet
#

It'll be a really bad game

light bay
late viper
#

I wouldn't suggest posting shady exes even as a joke, it might get you banned lol

alpine swan
#

don't worry xD

#

its nothing

misty kelp
#

I doesn't work.

late viper
#

Bruh

light bay
#

PEGASUS

alpine swan
#

Might be bugged

#

try right click, then "run as administrator"

olive magnet
#

Try restarting your computer

misty kelp
alpine swan
#

Ye prob, but I can't upload such a huge file on discord

late viper
alpine swan
#

@late viper U sure he ain't trolling us

misty kelp
late viper
late viper
woeful sentinel
misty kelp
late viper
#

if you say so 🤷‍♂️

hollow crown
#

@alpine swan Don't send random exes and don't post reaction gifs

alpine swan
#

Sorry ):

olive magnet
#

I'm not sure who's trolling who anymore

#

such is life

limber dome
#

hi i need help with state machine behaviours
so
in a behaviour script how can i get the rigidbody componenet of the game object to which the behaviour is attached

#

hey

turbid heart
limber dome
#

see

#

if i use findobjectwith tag

#

it will break

#

so this thing is an enemy

#

and i want get its rigidbody to move it

#

but if there are two enemies with the same tag

#

it wont work as it will get the rigidbody of the srong enemy

#

you understand?

ruby karma
#

no

limber dome
#

so see

#

I have two enemy

#

both have ta enemy

#

now if use findObjectwithtag(Enemy)

#

it may get the wrong enemy

#

i want it to to get the enemy to which the behaviour is attached

ruby karma
#

Which behaviour?

limber dome
#

this is teh state machine

#

the behaviour is attached to the attack anaimation

misty kelp
#

Hello, I need help with a boiling minigame for a cooking game.

ruby karma
limber dome
#

oh kk

#

so then i ca only have one enmy at a time

#

sad

misty kelp
#

Please answer me?

ruby karma
#

its possible. Just do whatever you want to do when you ask the animator to play the attack animation

#

from a Monobehaviour rather than a StateMachineBEhavior

turbid heart
#

the animator parameter is referring to the animator. get the gameObject from the animator using .gameObject, then it's just like any other GameObject

ruby karma
#

oh I see

turbid heart
#

i'm assuming they're using the predefined methods when inheriting from StateMachineBehaviour

abstract olive
misty kelp
abstract olive
#

Show your design and exact steps you want in this minigame.

#

Mockups etc.

misty kelp
#

I want all the steps from cooking Mama.

misty kelp
late viper
#

😂

modest cargo
abstract olive
#

So let's see what you have so far?

misty kelp
abstract olive
#

Oh, you're asking for it to be done for you?

abstract olive
#

Don't spam this discord with that nonsense. If you want to hire someone, there's a section in the forums. Find the link in #854851968446365696.

abstract olive
#

Well, this isn't the place to ask for handouts. Unless you're going to show your work, so people can help you with issues, don't post about this again.

abstract olive
#

That's the rules. You're not a special case to be exempt from them.

flint geode
#

hit doesnt exist, what do i put instead

abstract olive
#

What are you even trying to do?

#

I assume you want to raycast from the mouse position?

flint geode
#

so

#

im trying to

#

uh

#

so i have an object

#

i want to make it interactable

#

i got a script for interactable

#

public class Interactable : MonoBehaviour
{
    public float radius = 3f;

    void OnDrawGizmosSelected ()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}
#

not done

#

yet

#

but it says radius and stuff

#

but i now need to add it to my player controller.. So when i right click it sees whether its interactable

#

i think thats what im trying to do

#

lol

abstract olive
#

You want to learn about raycasting then.

flint geode
#

ah alr

abstract olive
#

Specifically using raycasting from the mouse position into the world. Getting the object the ray hits and checking if it is a Interactable, as you're already doing.

flint geode
#

alr

#

thanks

#

o noes

#

@abstract olive help

#

i got rid of that, cause i was gonna do it in another script

#

but now my fixed update isnt working

#

why?

#

apparently its declared but never used

#

and its back to how it was b4

#

?

dusky wagon
#
public float speed;
    public float turnLimit;
    bool swingingLeft;
    Rigidbody2D rb;
    public float waitAtLimit;
    float currentCooldownTime;

    private void Awake()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        currentCooldownTime = waitAtLimit;
    }



    private void FixedUpdate()
    {
        if(swingingLeft)
        {
            if (rb.rotation <= turnLimit * -1)
            {
                SwitchDirection();
            }
        }
        else
        {
            if (rb.rotation >= turnLimit)
            {
                SwitchDirection();
            }
        }
        
        if(currentCooldownTime <= 0)
        {
            if (swingingLeft)
            {
                rb.velocity = new Vector2(speed * -1, 0);
            }
            else
            {
                rb.velocity = new Vector2(speed, 0);
            }
        } 
        else
        {
            currentCooldownTime -= Time.deltaTime;
        }
    }

    void SwitchDirection()
    {
        if(swingingLeft)
        {
            swingingLeft = false;
        }
        else
        {
            swingingLeft = true;
        }

        currentCooldownTime = waitAtLimit;

    }```

I have this script to make an object that has a hinge collider 2D swing to the left and right until it hits a certain angle and then change direction. The script works but when I try to connect another object to that object that is supposed to swing with it, it breaks and over turns
dusky wagon
#

I did the probably most obvious thing and made it a child object of the swinging one, but that also makes it rotate with the parent object which I am trying to disable

stray obsidian
#

Hi, im new to unity and programming so i have a lot of problems with my code. Is this the place where i can ask for help ?

turbid heart
stray obsidian
#

Alright, thanks

languid turtle
#

how would i go about pausing my players movements until i press a key? making a flappy bird type game and dont want the player to start falling right when the game starts but only when i start pressing the space bar

snow willow
languid turtle
#

awesome, thank you!

eternal tundra
#

Hello! I'm having some trouble trying to figure out how to set up proper camera borders with the pixel perfect component. I was thinking of creating a border the size of the camera ortographic size, but I don't know how to approach that.

eternal tundra
#

A border the player collides with so he cant get out of bounds

outer wagon
#

Hello, I'm trying to drag one prefab. but if i'm out of the Collider, it stops moving, is there any way to save the collider I touched and transform his position even if i'm out of his collider?

        if(!_dragging) return;
        var fingerPos = GetFingerPos();
        Vector2 touchPos = new Vector2(GetFingerPos().x, GetFingerPos().y);
        if(GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos)){ //Pretty sure the fail is here
            transform.position = fingerPos;
        }
    }```
snow willow
limber dome
#

Hi

#

so i want my enemy to not collide with the player

#

as in go through it

#

but i want it to trigger a player damage function

#

how do i do that

grand coral
desert cargo
#

What does setting SpriteRenderer.color do under the hood?

snow willow
desert cargo
#

Right, so it will create a new material instance?

snow willow
#

nah

#

Renderers have a certain amount of leeway (somehow) to set shader params that override the material settings

desert cargo
#

Hm.

#

So I did this huge optimisation pass in this project

snow willow
desert cargo
#

And in it I removes all of my SpriteRenderer.color assignments and replaced them with shared materials of various colors

#

And this at the time reduced draw calls significantly

#

But unfortunately I didn't make very good commit messages

snow willow
desert cargo
#

True

#

Unfortunately the code is in C++ so it's not in the github reference

limber dome
#

Hi

#

rb.addforce doesnt work

#

I want to do knockback

#

btw i am using rb.velocity for player movement

#

and i want to add knockback to player

knotty barn
#

You override added forces when you use rb.velocity

#

You either need to use forces for movement or handle the forces manually with your rb.velocity

limber dome
#

oh kk

#

also is using animation for knockback ok

desert cargo
# limber dome rb.addforce doesnt work

calling AddForce will not do much if you run it for a single frame. The "force mode" argument allows you to use different force modes (which may be more appropriate)

unreal sun
#

hello, i dont want my ball to pass through this box when its droppingm how do i do that?

dusky wagon
#

I want an object to follow another object exactly, but without changing the rotation when the object it follows changes the rotation, so I cant just make it a child object of the object I want it to follow. I made a script that changes the position of the object to the position of the object I want it to follow each frame, but it looks a bit wonky. Is there a better method to do it?

abstract olive
#

Try using the Position Constraint component on your follower instead.

dusky wagon
abstract olive
#

Nope. The point of the various constraint components is so you don't have to child it.

dusky wagon
#

And how exactly does it work?

#

I have given it the position constraint component but Im not sure how I can use it to make it follow an object

#

Oh never mind I see

#

The sources seem to be what I need

abstract olive
dusky wagon
#

Thanks!

earnest viper
#

hello

#

so I made a physics system with Transform's for fun

#

It works well but has one problem

#

the player sinking 0.08 units into the ground

#

its not much but its noticable

dusky wagon
#

What exactly do you mean by "physics system with Transform's"?

earnest viper
earnest viper
#

really dumb and basic but it works

dusky wagon
#

And why dont you use a rigidbody?

earnest viper
#

rigidbodies are pretty cool

merry tundra
#

anyone know how can i change the pivot point in the script ?

lean lark
#

@merry tundra take a look at the sprite import settings, there's a pivot setting

#

I'm working on a BOIDs test scene and I'm stuck on getting them to avoid each other. Hoping someone can help with this vector math

I have a BOID that knows it's position and the position of it's nearest neighbor. What I want is to tell the BOID to turn away from it's nearest neighbor. Given the two vector points, how can I tell the BOID which way to rotate?

I'm working with Vector3.Dot but it's only able to tell me if the object is in front or behind, not left or right

merry tundra
lean lark
#

ah I see

#

one sec

#

sorry mate seems like that's not straightforward, this is the most useful thing I found

#

idk your needs but maybe you can just set up an array of several sprites and have a different version for each pivot point?

#

best of luck

merry tundra
#

thx bro

shadow nebula
lean lark
#

my thought is that I can factor in the Vector3.Dot

#

so that it turns away by a set speed, and moreso if it's pointing directly at the object

shadow nebula
#

You could rotate the vector around the Z axis based on whether it is heading to the left or to the right of its neighbour

lean lark
#

I guess my issue is determining whether it's left or right

shadow nebula
#

Dot product should say that right

#

Based on its sign

#

If not then use Vector2.signedAngle or something along those lines

lean lark
#

hm maybe I need to better understand dot product

still tendon
#

Hey guys, I can't get Classname.Instance.gameobject !! Any idea why not??

lean lark
#

wouldn't directly left and directly right both return zero from dot product?

#

@still tendon can we see the code

still tendon
# lean lark <@456226577798135808> can we see the code

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

public class AIController : PhysicsObject
{

public float aiMaxSpeed = 7;
public float aijumpSpeed = 7;
public float aiDirection = 1;
public float aiChangeDirectionEase = 1;
public float aiDirectionSmooth = 1;
private bool isAIJumpping;
public float playerDifference;

private Vector2 raycastOffset;
[SerializeField] private LayerMask LayerMask;

[SerializeField] private GameObject _aiGraphic;
[SerializeField] private Animator _aiAnimator;

private RaycastHit2D aiLeft;
private RaycastHit2D aiRight;

protected override void ComputeVelocity()
{
    Vector2 aiMove = Vector2.zero;
    playerDifference = PlayerController.Instance
}

}

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

public class AIController : PhysicsObject
{

    public float aiMaxSpeed = 7;
    public float aijumpSpeed = 7;
    public float aiDirection = 1;
    public float aiChangeDirectionEase = 1;
    public float aiDirectionSmooth = 1;
    private bool isAIJumpping;
    public float playerDifference;

    private Vector2 raycastOffset;
    [SerializeField] private LayerMask LayerMask;

    [SerializeField] private GameObject _aiGraphic;
    [SerializeField] private Animator _aiAnimator;

    private RaycastHit2D aiLeft;
    private RaycastHit2D aiRight;

    protected override void ComputeVelocity()
    {
        Vector2 aiMove = Vector2.zero;
        playerDifference = PlayerController.Instance
    }
}
still tendon
turbid heart
#

Does your PlayerController script have an Instance variable?

shadow nebula
lean lark
still tendon
#

forgot making get{}

#

for new instance

still tendon
still tendon
#

Quick question guys, how can I refer to these sprites via single GameObject

#

Every part name is a sprite

shadow nebula
modest cargo
#

Guess it depends what you want to do with them
In similar situations I've used GetComponentsInChildren

still tendon
still tendon
abstract olive
#

The plural version will return an array of matches.

modest cargo
#

And from all children, even recursively

still tendon
#

sorry had no idea there was a plural version!😅

bronze anvil
#

Is anyone familiar with rule tiles? While defining individual rules, does the order matters?

#

I'm generating them through the code, and it seems it matters.

#

Also looking at the inspector, the rules are draggable, I'm guessing for the same reason.

desert cargo
#

How would I go about generating a custom mesh and using it as a sprite mask?

hollow remnant
green anchor
#

how do you make transition between rooms like binding of isaac?

#

creating scene for every room (i dont think so) or using panel for 0.5 sec make everything black then teleport to other room

#

or anything else any ideas?

turbid heart
desert cargo
#

How you make the rooms is a different consideration, but you could create a cinemachine virtual camera in every room and enable it when you want the camera to go there

#

I can't recall how isaac does it

green anchor
#

instead of creating virtual camera in every room i can change position of camera

desert cargo
#

a "virtual camera" is a camera position

knotty barn
#

Yea virtual cameras are "changing the position" on steroids

compact knoll
#

I'm making an isaac clone, though I'm only using the basic sized rooms like in the flash version. What I do is lerp the camera to the room center point when I change rooms to give the feel of actually moving between rooms rather than just teleporting the view

turbid heart
compact knoll
#

The rooms themselves are pre-designed layouts, but I am generating the dungeon at runtime to make unique floor layouts.

#

I put the room objects into arrays on a script able object that my dungeon generation references and instantiate the room objects and grab the layout from the array. Although I may look into writing a script to generate the layouts of each room at runtime depending on how bloated the current method gets with more room layouts

turbid heart
#

i see. thank you for sharing

bronze anvil
# distant pecan Yes

Any suggestion where I could find a tutorial that explains how is the order used in the algorithm? Thanks!

#

Even if I check the Unity official tutorials, they never mention that the order is important.

#

Found this in tilemap extras, but it's not clear: "For optimization, please set the most common Rule at the top of the list of Rules and follow with next most common Rule and so on. When matching Rules during the placement of the Tile, the Rule Tile algorithm will check the first Rule first, before proceeding with the next Rules."

compact knoll
#

Think of it like if statements, it checks each condition in order. So it will perform fewer checks for the most common ones if they are higher in the list

still tendon
#

so im working on a little project in unity (v.2020.3.15f2 64-bit) and im having a hard time with making a movement script in bolt what i need to know is how i move the player 5 steps forward relative to its position can anyone help?

still tendon
still tendon
outer wagon
#

I've store a grid in a Array2D and want to detect his limits for doesnt letting anything move out of that array grid, PraetorBlue told me using that array2d as information instead of physical collision, but I didnt find out anything out on the internet, anyone has a link for learning how it works or know how to do it?

snow willow
#

so you just make sure the x and y coords are > 0 and less than that length

#

as for colliding with other tiles in your grid you just check if there's a tile there already.

outer wagon
#

i'll try, thanks for the tip

misty kelp
#

I would like to make a game with the same steps as Cooking Mama and Cooking Academy, but I don't know the scripts.

outer wagon
late viper
faint hollow
#

Looks like everything it's okay

#

but then

#

I have no idea what is the error hahahah

#

I'm dying right now, every thing I do it has a new error aaaaa

topaz root
#

Not sure if it's the cause of the current issue, but I believe line 28 should read tempPos.x = player.transform.position.x;

faint hollow
#

I solved

#

It was because I removed the player before and forgot to add the player tag to the player

#

god

#

I'm so noob at this

languid adder
#

How do I turn a sprite sheet into a pallette?

forest token
#

like a tile palette?

#

@languid adder

languid adder
#

te

#

*ye

#

@forest token

forest token
#

k

#

so you must select it

#

and in inspector you must change single to multiple

#

and then slice it in sprite editor

#

now it depends if you want normal palette or pallet with rule tiles

#

@languid adder

languid adder
#

What's rule tiles?

#

@forest token trying to slice it rn

forest token
#

rule tiles are tiles, that are in script, that unity 2D extras create for smart tile placement

#

normaly, u must select tiles that you want in some place

#

but this will change them automaticly

alpine swan
#

In your case you can make a rule tile, to make things easier.

forest token
#

but you must download 2D extras

languid adder
#

How I edit the positions of this?

forest token
#

with the move tool

languid adder
#

Where's the move tool?

#

@forest token

#

this?

#

I click and drag and won't move

forest token
#

actually i dont have any idea, i never had to move it xd

stoic moon
#

I have this code, and it worked fine until I added the commented out bit in the raycast script. It then threw me an error, and when i commented it out, it threw me another error that the object was not set to an instance of an object. I have the player variable hooked up in the editor as normal. Whats happening here? I know I dont have any duplicate scripts on my enemy, so this is really wierd

turbid heart
#

it might not have hit anything

stoic moon
#

nope, did that and I'm still getting an error

#

whats weird is it worked perfectly 10 minutes ago

#

I am genuinely very confused

#

I tried using gameobject.find, same error

#

looks like the error is coming from the canseeenemy.collider if statement?

#

Yep, the collider.tag is the part that is being a problem. How do i fix it?

snow willow
#

RaycastHit2D itself is never null

#

but the collider field may be

still tendon
#

hello, i was wondering if there was a way to make one sprite loop around?

#

like if it reaches the edge of a spritemask or something then it starts coming through from the opposite side

snow willow
#

Definitely with a custom shader
Possibly with the right tiling settings with a built in shader

#

probably not as a sprite though, but as a Texture2D

still tendon
#

okay thanks

#

do you have any ideas about how i could do that?

timber pendant
#

Guys, I have lag problems prefabbing a tilemap grid gameobject. As I understand it, prefab tilemaps are "better editted in prefab mode". BUT I want each of my levels to have its own tilemap (thus editing the base prefab is useless). I need it because the grid is kinda complicated, being made of multiple layers etc.
Anyways, if I make a prefab variant for every level it STILL DOES NOT WORK: It lags the same way as it was lagging on editing the scene's gameobject. So is there another way to make prefab tilemaps to work properly, or I will have to unpack them and make them separately for each scene? (In which case if I need to make a change in all levels I am screwed?)

spring zephyr
#

recently i found that somewhere in the Project Settings is a setting that can allow a 2d object to overlap based on position. But now i cant find it.. anyone remember where or what it was called

timber pendant
#

you probably want to sort by y. Change y to 1 and z to 0

#

And sort mode custom axis*

timber pendant
#

I guess I will unpack my tilemap prefabs. Weird though that unity basically does not allow tilemaps to be prefabed properly

sullen zodiac
#

Can somebody help me with a simple but weird problem im having?

timber pendant
#

what is the problem

sullen zodiac
#

can i dm you?

timber pendant
#

if you want?

sullen zodiac
#

sure thenm

stoic moon
#

hello, I have a raycast script that moves an enemy when a raycast returns true, and a debug raycast that shows me if a line that hits the player happens. When i go into my game, the code sometimes works, but randomly acts like something is blocking it or it stops recognising terrain as blocking it if the object goes far away enough. What's going on?

#

the script is kinda long so if anyone needs it i'll put it in a pastebin or something

snow willow
stoic moon
#

nope, lemme try that

spring zephyr
stoic moon
#

tried this line to print out the object:Debug.Log(hit.transform.gameObject);(My raycast is the variable hit), but I get an object reference not set to the instance of an object?

#

I tried adding a rigidbody 2d to the enemy, now the raycast has stopped working entirely

snow willow
#

you need to check for that

lament oxide
#

So Unity physics is driving me up the wall... I found that if I constantly apply torque and add force to a rigidbody 2D, when I enable a collider it will fling the object half way across the screen and rotate it the opposite way... Here is some bad code and the inspector. I am just trying to make a simple version of asteroids but keep finding these bugs.

//script to apply force through a button on screen
void FixedUpdate()
    {
        //if the player holds the button down we accelerate
        if (pointerDown && Player) //If the pointer is pressed and the player is in the scene
        {   //Velocity (acceleration)
            Vector3 vel = _rb.velocity; //this gets speed of player
            if (vel.magnitude < maxSpeed) //if speed under max
            { _rb.AddRelativeForce(Vector2.up * thrustInput * 10); } //increase player speed
        }
     }
//script on player sprite
void FixedUpdate() 
        {   //rotation
            turnInput = Input.GetAxis("Horizontal"); //arrow keys turning player
            float rtn = _rb.angularVelocity; //this gets rotation speed of player

            if (rtn < 150.0f || rtn > -150.0f) //if rotation is less than 150 and greater than -150
            { _rb.AddTorque(-turnInput * 10); } //add torque
        }
snow willow
lament oxide
#

Basically, I am pushing right arrow and it's showing a positive force, but applies a negative force if the player is also accelerating

#

Until I let go of the the arrow and press it again

snow willow
#

can you explain what you meanby "positive" and "negative" force?

lament oxide
#

player meant to go forwards, player goes backwards

#

Oh wait, sorry I think I found the problem already 😅

#

I had a check to limit the acceleration and slow them to a stop if they reached a certain speed, it was badly done

stoic moon
#

My raycast is colliding with the Enemy object(the script's object) and nothing else? How can i stop this from happening?

snow willow
#

or temprorarily put the Enemy's collider into the Ignore Raycast layer, do the raycast, and put it back

stoic moon
#

Managed to somehow get it working, but whenever it hits the player, it freaks out with a nullreference exeption and stops the code working that i have in place

#

As in I barely chaged anything from my original code

snow willow
stoic moon
#

The thing is, the code sometimes does start working? and the error is thrown only when it detects the player, as it i put the player behind an object it doesnt throw me the error

snow willow
stoic moon
#

I'm only using this in the if statement:hit.collider.name == "Player"

#

and it's name is Playeer

#

Player sorry

snow willow
stoic moon
#

oh ok

#

all this raycast crap is hurting my head

#

would it work if I just added an empty collider under the enemy and checked if that collided with the player?

#

as a trigger of course

snow willow
#

I don't know. No idea what your game is supposed to be doing or what you're trying to do

stoic moon
#

Oh sorry I may have forgotten about that

#

I was just trying to see if the enemy could see the player

#

And stop it from seeing through walls

#

so the collider wont work crap

#

Raycasting is so confusing

#

Imma do it anyway, it'll somewhat work anyway

thin stirrup
#

help

#

i have soooooo many errors

#

only for a movement script

#

pls help

snow willow
#

maybe start by sharing your script and the exact error messages

thin stirrup
#

this isnt even half of the errors

snow willow
#

Seems like some basic syntax errors

thin stirrup
thin stirrup
snow willow
#

end of line 10, you need GetComponent<Rigidbody2D>();

#

the () is needed

thin stirrup
#

oh

snow willow
#

that will probably clear up most of them

thin stirrup
#

okay done

thin stirrup
snow willow
#

which are?

thin stirrup
snow willow
#

start with the top one

thin stirrup
snow willow
#

line 13

quartz glen
#

after if start {

thin stirrup
snow willow
thin stirrup
snow willow
thin stirrup
quartz glen
thin stirrup
#

another error came :/

snow willow
#

line 14 and 19

#

you're using ( and )

#

it should be { and }

thin stirrup
#

ohhh

snow willow
#

That's why it's so damn confused

thin stirrup
#

all errors are gone

#

tysm

#

but the script isnt working

snow willow
#

well, yu never gave a value to speed right?

#

So speed is going to be 0

thin stirrup
#

oh

#

crap i forgot to give a value

quartz glen
#

change to public float

#

then you can easily adjust value in inspector

thin stirrup
thin stirrup
stoic moon
#

how do you set a variable of a parant object to a variable of a child object?

flint hollow
#

you can try referencing the parent varible to the child object via script

stoic moon
#

nevermind

flint hollow
#

you fixed it?

wild iris
#

Hi, how do I spawn objects randomly only on the x - axis? I'm new to Unity and C#. I currently have this but it doesn't work, any help is appreciated. enem1.transform.position = new Vector2(screenBounds.x * 5, Random.Range(-screenBounds.y, screenBounds.x));

snow willow
#

although you haven't really explained where you're gettin this screenBounds thing from?

thin stirrup
#

its for a package

#

should i delete the camera

thin stirrup
#

help

humble forge
#

impossible to help without seeing the code

#

can you show those lines the errors are about?

stoic moon
#

With this code, my raycast works fine while the enemy is not withile los of the player, but as soon as it is, it does not run the code inside the if statement for if its collider.tag is a player one. It should be drawing a green line, but it does literally nothing. When i move it back behind a wall, it returns to normal behavior?

wary briar
#

how can get my art that i made in inkscape into my unity project? i want to make a sprite sheet out of my pixel art that i made but there are 0 tutorials that i could find for my situation can anyone here help?

stoic moon
#

Actually, it seems like it stops raycasting entirely, but only when it sees the player

snow willow
#

Either change the second parameter to a direction vector, or use Physics2D.LineCast instead which accepts two position parameters

#

Linecast seems like it would make more sense in this case, in my opinion, but you can make it work with either.

stoic moon
#

Cool

#

Looks like linecast worked, thanks so much!!

dapper stump
#

what is the best way to smoothly rotate a 2d object to a certain angle?

lean estuary
#

Quaternion.Lerp

#

Vector2.SignedAngle for relative angles

dapper stump
#
Quaternion target1 = Quaternion.Euler(0,0,-60f);

transform.rotation = Quaternion.Lerp(transform.rotation, target1, rotateSpeed);```
#

i did this and it was more of a snappy movmenet

#

transform.rotation = Quaternion.RotateTowards(transform.rotation, target2, rotateSpeed);
i used this and it worked, is this a good solution?

lean estuary
#

t in a Lerp is "time" ranging 0 - 1. If you want smooth movement you need to animate it moving from 0 to 1

dapper stump
#

alright thanks!

#

why am i getting a error if i want to know if the velocity of x is 0?

mint geyser
#

you want myRigidBody.velocity.x == 0

lean estuary
#

you are assigning ^^

mint geyser
#

not myRigidBody.velocity.x = 0

dapper stump
#

ohhh

#

thank you i thought that was only for if statements

#

would I need to add a *Time.Deltatime after the
rotateSpeed

mint geyser
#

well what is rotateSpeed

dapper stump
#

how fast i was it to rotate currently
float rotateSpeed = 0.7f;

mint geyser
#

ight

#

yeah you wanna add a * Time.deltaTime

#

although you will have to make rotateSpeed bigger

dapper stump
#

yep that works

#

i thought that rotate speed was a value between 0-1 only

#

thanks for the help

mint geyser
#

np

lean estuary
lean sphinx
#

hey, can someone help me with this one? i need to set the position of the firepoint of the weapon to be on certain Y values, i already can recognise which sprite it has, and i have made a public array of vector 3, so then i can put the Y values that should be, but when i code for example

"transform.position = array[index]"

it goes to a completely different one

mental idol
#

It returns a different value in the array?

lean sphinx
#

for example

#

the Y value in the array is 0.5

#

when it should be 0, 0.5, 0 in the transform

#

it goes like this

snow willow
#

i.e. its position relative to its parent object

lean sphinx
#

ok, let me try with localPosition

#

it works now

#

Thank you

shadow sluice
#

How do you put a Texture2D with multiple sprites into a sprite array?

woeful temple
#

hello simple question
where can i put my out in a 2d raycast?
my line of code

//need to put out topRay somewhere but cant find where
Physics2D.Raycast(transform.position, transform.position + transform.up * rayDist, blockMask);
snow willow
#

please check the docs

woeful temple
#

then how do i get a reference?

snow willow
#

look at the example code

woeful temple
#

ok thanks

#

ok so I got a new problem, how do I prevent the raycast hitting itself?

#

it keeps on detecting the object the raycast comes from

snow willow
# woeful temple it keeps on detecting the object the raycast comes from

notice that there is no "source' or "object this came from" parameter. The raycast is not aware of any such concept. TO avoid hitting a certain obejct you can either:

  • Put that object on a particular layer and use a layer mask that doesn't hit that layer for your raycast
  • Temporarily move your object to the "Ignore Raycast" layer, do the raycast, then set the layer back
woeful temple
#

ok, thought there would be a function

snow willow
woeful temple
#

how would i use that?

snow willow
#

it's a parameter in the raycast function

woeful temple
#

ok

#

ill just go with the changing of layers

#

wait but will this still work if i have multiple objects doing the same thing?

#

i have multiple objects with the same script trying to detect each other

#

yep there not detecting each other properly

snow willow
#

asssuming you revert the layers properly

woeful temple
#
LayerMask prevLayer = gameObject.layer;
        gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
        top = Physics2D.Raycast(transform.position, transform.position + transform.up * rayDist, blockMask).transform!= null;
        bottom = Physics2D.Raycast(transform.position, transform.position + -transform.up * rayDist, blockMask).transform != null;
        right = Physics2D.Raycast(transform.position, transform.position + transform.right * rayDist, blockMask).transform != null;
        left = Physics2D.Raycast(transform.position, transform.position + -transform.right * rayDist, blockMask).transform != null;
        gameObject.layer = prevLayer;

like this?

snow willow
#

yes

woeful temple
#

weird let me try again

snow willow
#

your second raycast parameter is not correct though

#
transform.position + -transform.up * rayDis``` < why are you incorporating the position into the ray direction parameter?
#

also what is blockMask?

hoary ginkgo
woeful temple
snow willow
#

whatever blockMask is, you're passing it into the "max distance" parameter

woeful temple
snow willow
#

if you want to apply a layermask to your raycast in 2D, you need to use the ContactFilter2D parameter

snow willow
woeful temple
#

ohh yea ur right

#

yea wait lemme fix it

snow willow
#

it should just be, e.g. -transform.up

#

rayDis should go into the third parameter

hoary ginkgo
#

Can someone tell me the best way to save the line shopPanelGO{btnNO].setactive false

#

I mean between play sessions?

snow willow
woeful temple
#

so i revamped my code

left = Physics2D.Raycast(transform.position, -transform.right, rayDist, blockMask).transform != null;

so this is good now?

hoary ginkgo
#

How would I save it to a player pref that was my original idea but it is not a int float or string

woeful temple
#

wait but now none of the blocks are detecting each other

snow willow
snow willow
#

it should just be int prevLayer = gameObject.layer;

hoary ginkgo
#

I think the problem is really in my start function. I believe it is because I am setting all panels true

snow willow
woeful temple
snow willow
#

where did you set it up?

#

in the inspector?

woeful temple
#

yea

snow willow
#

ok good

woeful temple
#

nop still doesnt work

snow willow
#

show the code now?

woeful temple
#
   void CheckAdjecentBlocks()
    {
        int prevLayer = gameObject.layer;
        gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
        top = Physics2D.Raycast(transform.position, transform.up, rayDist, blockMask).transform!= null;
        bottom = Physics2D.Raycast(transform.position, -transform.up, rayDist, blockMask).transform != null;
        right = Physics2D.Raycast(transform.position, transform.right, rayDist, blockMask).transform != null;
        left = Physics2D.Raycast(transform.position, -transform.right, rayDist, blockMask).transform != null;
        gameObject.layer = prevLayer;

    }

#

im running it in update

snow willow
#

ok and how are you checking if it's working?

woeful temple
#

the top, bottom, etc are bools

snow willow
#

and you're checking them how?

woeful temple
snow willow
#

what's rayDist set to?

woeful temple
#

.5f

#

a block is 1x1

snow willow
#

Then it wouldn't work ever right?

#

.5 only reaches out to the edge of yourself

#

as a 1x1 block

#

what if you make rayDist bigger?

woeful temple
#

ok lemme try

snow willow
#

remember the rays are coming from the center of each block

woeful temple
#

ohhh yea

#

so now its works

#

thanks alot

snow willow
#

cool

woeful temple
#

i need to check the blocks so that i could connect them

dapper stump
#
    
 
    void OnTriggerEnter2D(Collider2D other)
    {
      
      Vector2 bounceVelocityToAdd = new Vector2 (xBounce, 0);
      Rigidbody2D itsRigidBody = other.GetComponent<Rigidbody2D>();
      itsRigidBody.velocity += bounceVelocityToAdd;
      
      print(itsRigidBody.velocity);
    }
#

When I run this code my player doesnt have the x velocity

#

however if i change the code and give it y velocity it works

#

is this a physics related issue?

dapper stump
#

when i comment out this line it the x velocity works as well

snow willow
#

This is the main issue with the "directly setting the velocity" technique.

#

Using an AddForce technique this wouldn't be an issue.

dapper stump
#

i see

dapper stump
dapper stump
#

myRigidBody.AddForce(new Vector2(5, 0), ForceMode2D.Impulse);
I did this and yet again the x velocity didnt change but the y did when i tried to make it change

wind blade
#

Hello guys

#

Small question

#

Is there a way to trigger scene changes with like a door??

#

and how do I save all the state of the player, like health, money, armor etc?

snow willow
dapper stump
#

this fixed it thanks
Vector2 playerVelocity = new Vector2(myRigidBody.velocity.x + control * speed, myRigidBody.velocity.y);

wind blade
dapper stump
toxic pilot
#

https://paste.myst.rs/u1beyq49

Cannot read instance id from Json file with Tilemap Tiles information in WebGL. Does webGL not read instance id as these are being saved in json. What's the solution?

polar furnace
#

does someone know why my player can't jump and moving at the same time?
when i'm moving and jumping it'll first jump then move horizontally while it's still in the air

#

Like this

glad ibex
#

Hello everyone ! I'm working on an educational game for kids and one of the stages requires you to draw circles with touch. how can i make the player able to draw using the touch of android and how can i compare what he draw to circles ?

glad ibex
#

i found a way to draw with linerenderer but the only issue now is how to detect if he drew a circle or not

modest cargo
glad ibex
#

in some other exercises i need the player to draw lines which should be easy by using a box collider and the last point of the linerenderer but I cant do that for the circles

still tendon
#

One solution, is to listen to the touch positions

#

Calculate a distance from a certain point, then proceed to store those distances within a buffer

#

If the distances are within a definite limited range

#

then you could say they've drawn a circle, since a circle is a line of points which are equally distant from a center

#

For the drawing process you could use a SpriteShape

#

which allows you to create smooth curved lines

glad ibex
#

thats genius thnx

still tendon
#

Although a shader implementation is possible too

glad ibex
#

SpriteShape instead of linerenderer ?

still tendon
#

yes

#

If you are good with basic coloured lines, it's also okay

glad ibex
#

I'll look into it thnx again

#

making the lines look like they are drawn be a crayon would be cuter

still tendon
#

Then sprite shape would be the way to go, although it requires spending certain time researching on how to implement exactly what you desire

#

Good luck with it! 😄

stoic moon
#

This code(Which deals damage to my player when it collides with an enemy) is Only running once when the enemy collides with my player, and I have to move away and come back to the enemy before it can deal damage again. How can I get this to work constantly while the enemy is colliding with the player?

stoic moon
#

Nevermind, figured it out

languid adder
#

Anyone know why this error happened?

still tendon
#

GetButtons may be trying to access some method or field from a null value

languid adder
#

Like where can I find this null value?

still tendon
#

Which one is the line 23?

languid adder
#

@still tendon

dusky wagon
#

Does anyone know how I can modify a rule tile script to change what it counts as a neighbor?

#

I want it to count everything on the same tilemap

still tendon
#

That's because not all GameObjects with the tag

#

contain a component 'Button'

#

thus when you try to access fields relative to the 'Button' class

#

it fails, because there's a null instead

languid adder
#

Sooo. how do I solve it

still tendon
#

Make sure all the GameObjects with the tag you've got there, have a Button component

sullen zodiac
#
using UnityEngine;

public class Dash : MonoBehaviour
{
  public float dashCooldown;
  public bool canIDash = true;
  public Vector2 savedVelocity;
 
  void Update () 
  {
      if(dashCooldown > 0)
      {
          canIDash = false;
          dashCooldown -= Time.deltaTime;
      }
      if(dashCooldown <= 0)
      {
          canIDash = true;
      }
      if(Input.GetKeyDown(KeyCode.LeftShift) && canIDash == true)
      {
          savedVelocity = GetComponent<Rigidbody2D>().velocity;
          GetComponent<Rigidbody2D>().velocity =  new Vector2(GetComponent<Rigidbody2D>().velocity.x*3f, GetComponent<Rigidbody2D>().velocity.y);
          dashCooldown = 2;
      }
  }
}
#

why this isnt working

#

like

#

there`s no error

#

it just

#

doesn`t happen

torpid coral
#

If you add a debug.log to the keypress check If statement, does it print in console?

sullen zodiac
#

i`ll try that out'

stoic moon
#

The raycast is not doing anything(returning null), even when I put the player on the correct layer(8). Whats going on?

snow willow
#

should be 1 << 8

#

I recommend simply using a public LayerMask layerMask; variable and configuring it in the inspector instead.

stoic moon
#

Ah ok now it works

#

How would i Invert that, so that it looks everywhere but a specific layer?

snow willow
#

layerMask = ~layerMask;

stoic moon
#

This is my new code(with the layermask variable on top, and the in the editor set to my enemies), the debug lines flicker and start/stop working at random, and it doesnt ignore my enemies

snow willow
stoic moon
#

yep figured that out

#

putting it in the start method worked

#

thanks so much for your help!

desert cargo
#

Is there some way to modify the vertex colors in a sprite mesh?

#

I guess they don't have the values?

wild pivot
#
 public Button btn;

    public Camera mainCamera;


    void Start()
    {
        btn.onClick.AddListener(moveObject);
    }

 
    void Update()
    {
        Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);

    }

    public void moveObject()
    {
        
        
        
    }
#

Anyone know how i can use the 'mousePosition' vector3 in the 'moveObject' function

turbid heart
#

declaring it inside Update means it only exists within Update's scope. if you declare it like your Button and your Camera, everything in that class can access it

wild pivot
#

i need it to be in update tho

turbid heart
#

i said declare it outside. You can assign it in Update

wild pivot
#

oh ok

#

thanks for you help 👍

still tendon
#

Help! Physics2d.Raycast is not working or something I dunno, I debug the code and every value is 0 or null for the object which is catching value of Raycast... I don't know if this is the problem why my character is not detecting ledges, but it could be

snow willow
still tendon
snow willow
#

or the thing you're trying to hit doesn't have a collider

#

or is in the wrong layer

still tendon
#

On fucking point bro, thanks! 👍

alpine swan
#

Someone have any idea how to fix this. The wall down there is made from two parts, the top one has a sorting layer of 1 and the bottom one a sorting layer 0, the weapon also have a sorting layer of 1. Any ideas would be great

#

The sword is rotating towards the mouse position

stoic moon
#

I have a gun object that rotates towards the mouse position. When i fire a bullet, I want to have it face the same direction as the gun. How can I do this?

alpine swan
stoic moon
#

Thanks

#

How do I check if a gameobject with a collider of trigger collides with another object?