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

1 messages ยท Page 22 of 1

north ridge
#

Don't post same message in multiple channels

still tendon
#

ok

plush coyote
#

@thick geyser Do the things you are trying to hit have actual colliders?

thick geyser
#

yes

#

would you like me to take a video?

ruby karma
#

can use Debug.DrawRay/Line to visualize the raycast

#

always do ^ when raycasts aren't working as intended

thick geyser
#

oh ok, do i just copy the raycast part into that?

ruby karma
#

look up the documentation on how those work (: Similar to raycast overloads, but not exactly the same

plush coyote
#

do this line below your raycast

Debug.DrawLine(transform.position, transform.position + new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")), Color.red);
thick geyser
#

I see, let me try that

plush coyote
#

Just to see if it is the right direction

#

im assuming interactableDistance is not 0?

thick geyser
#

do I do the transform.position + the new vector?

#

no, its not

plush coyote
#

A better way of doing it would be

Vector2 dirOffset = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")) * interactableDistance;

Debug.DrawLine(transform.position, transform.position + dirOffset, Color.red);
ruby karma
#

.normalized

plush coyote
#

His raycast isn't normalized

#

so this would be more accurate

#

Unless the raycast auto normalizes

ruby karma
#

nah it doesn't

plush coyote
#

not actually sure about that

thick geyser
#

oop need to change the vector 2 to a vector 3

plush coyote
#

just cast the transform.position to a vector2

thick geyser
#

i fixed it

#

oh?

plush coyote
#

(Vector2)transform.position

thick geyser
#

that doesnt work

plush coyote
#

be more specific

thick geyser
#

it cannot be used like a method

plush coyote
#

you have a typo somewhere

ruby karma
#

post code

thick geyser
plush coyote
#

read what I sent again

ruby karma
#

new Vector2

plush coyote
#

no

#

the parenthesis go around the Vector2

ruby karma
#

and wrong encapsulation

thick geyser
#

sorry

#

learning lots of new stuff tonight haha

ruby karma
#

try to think why you are writing something before actually typing it. () basically encloses the values inside it into a single expression. so everything inside () is a single value

pulsar barn
#

how do i make game screen configuration before game starts

#

?

ruby karma
#

Unity dropped the native support for that

#

I remember reading somewhere you gotta do that on your own, they have an example somewhere

pulsar barn
#

so we cant do that anymore?

thick geyser
#

there is no ray being drawn, hmm

plush coyote
#

@thick geyser Is gizmos on?

#

in your scene / game view?

thick geyser
#

yeah

plush coyote
#

then are you sure interactableDistance isn't 0

thick geyser
#

its all checkmarked

#

its set as .2

plush coyote
#

try increasing it

thick geyser
#

alright

plush coyote
#

to like 5

ruby karma
#

hundred

thick geyser
#

oh there it is!

#

now I have superman laser eyes on my character lol

plush coyote
#

what is the radius of your character?

#

because anything under the radius as the distance value makes no sense

thick geyser
#

what do you mean by radius? the size of the sprite?

plush coyote
#

if your player collider has a .5f radius or something

#

then .2f as the interact distance will never exit your player collider

thick geyser
#

oh I see whats happening, it is too small

ruby karma
#

^ the maxDistance is from the centre of the player position.

plush coyote
#

it needs to be at least larger than the radius of your player

thick geyser
#

I guess i may have to make it scale for the up facing then

#

my game is a top down rpg, for context

ruby karma
#

that isn't context

plush coyote
#

that's what I thought, why would it need to scale up though?

thick geyser
#

oh wait, the ray is coming out of the head and not the collider at the feet

ruby karma
#

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

pulsar barn
thick geyser
plush coyote
#

just add the collider's center offset to your origin

#

of the raycast

thick geyser
#

oh alright

plush coyote
#

I forget exactly what it is called, but there is some property in there to get the offset

#

@pulsar barn Yeah, dont think that exists anymore in newer versions

#

you have to make an options menu instead

abstract mural
#

Yeah you need to make your own in the settings of your game

pulsar barn
#

i hope unity creator make setting like that again

thick geyser
#

the line is touching, but it isnt detecting

#

I may just be an idiot and missed something obvious though

#

@plush coyote

eternal hamlet
#

It might be detecting your players collider

#

You can use a layer mask to only detect the other object, or get an array of all collisions and loop through them

thick geyser
#

ok, I tried doing if (interactable.collider != playerObject.GetComponent<Collider2D>())

#

but that didnt work

#

ill try the layer mask then

plush coyote
#

the second parameter of the raycast is not your destination of the cast

#

it is just a direction

eternal hamlet
#

You can put in some more debugs to see if it's detecting any collisions

plush coyote
#

@thick geyser You should pass in a direction as the second parameter

thick geyser
#

oh yup that makes sense

plush coyote
#

if you want to be consistent, change your dirOffset line to this

Vector2 rayDir = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")).normalized;
#

and pass rayDir in as the second parameter of the raycast

#

then, add back your interactableDistance as the third parameter

thick geyser
#

oh you already posted something sorry

plush coyote
#

for the debug line, change it from using just the transform.position + rayDir to transform.position + (rayDir * interactableDistance)

thick geyser
#

already did that while you were typing lol

plush coyote
#

remember to normalize it

thick geyser
#

where do I normalize?

plush coyote
#

if you want to be consistent, change your dirOffset line to this

Vector2 dirOffset = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")).normalized;
thick geyser
#

ok, there

#

now let me try this out

#

hmm, still nothing. I need to set up a layer mask I guess

plush coyote
#

Send your current code

thick geyser
plush coyote
#

but yeah, you should use raycasts regardless

#

how about you debug.log in the outer if statement

#

to see if it hit anything

thick geyser
#

ok

plush coyote
#

So then your interactable doesn't have the tag you think it has

#

Either it has no tag, or one is misspelled

#

or it is hitting something else entirely

thick geyser
#

it was working before

#

it says
"Interactable"

plush coyote
#

Then I would set up the layermask

thick geyser
#

in both places

#

ok

#

thank you for all your help btw!

#

I know ive probably been a pain lol

plush coyote
#

not really, a lot of people here just ask for free code and copy paste without understanding anything

#

you actually understand whats going on though, so its easier to help

thick geyser
#

yeah, I dont like doing that. I have been dealing with this problem for 2 days, trying to fix it myself. Thats what I really want is to understand it for later

#

ok, I just had to set the player's layer to Ignore Raycast

#

Its working now!

plush coyote
#

it would be better to pass in a layermask as a parameter of the raycast

#

and have the interactables on a specific interactable layer

#

then you don't even need a tag for them

#

because your raycast would only be able to hit interactables

thick geyser
#

thats true, then I could make NPCs also on that layer

#

yeah

#

Im also planning on putting trigger colliders in front of each object or on the side I want a specific interaction for. Does that make sense in conjunction with the raycast?

#

I want that so I can also put things in corners and not worry about overlapping

plush coyote
#

what do you mean in conjunction with

#

like, the raycast would hit the trigger?

#

or the trigger would work independently

thick geyser
#

the trigger would be independent

#

so I could have the player have a different response interacting with the back or side of something

plush coyote
#

I cant really say if it would be better or not because I don't know how everything in your project is set up

thick geyser
#

yeah that makes sense, ill just have to see as I go

plush coyote
#

but you can always just ask here again if you have a specific issue with it

thick geyser
#

yeah, thanks! you've really helped me, and I've learned some good things to make my code better too!

#

see you around then when I break something again haha

thin wraith
#

Hello there, currently I;m having a project that uses LWRP(I know, it's an old one), I am having some issue when introducing pixel perfect camera into the project

#

The game was designed at 960x540 on 16PPU

#

so I set up the project that way

#

However after I switch the screen resolution into 1080p, or 4K, even if I've checked the stretch fill

#

The rendered image remains un-scaled

thin wraith
#

Never mind, just found it, I have to use 2D Renderer in order to make that actually works

humble tusk
#

i slide across the floor?

vocal viper
#

Hi everyone, soo my buddy created this youtube channel ( reallly stupid and funny contant ) and he has 57 subs. today is his birthday and i would be so happy if we can get him to 100 subs โค๏ธ thank uvery much to everone here. have a good day โค๏ธ https://www.youtube.com/channel/UCJkZVFN4sgZPePMW6WwTXZA

arctic moss
#

Guys I have one question

#

To designing of an object which software should I use for 2d

humble tusk
#

pixel art or?

tidal marlin
#

Photoshop or gimp?

#

Or aseprite

#

Gimp is open source ยฏ_(ใƒ„)_/ยฏ

arctic moss
#

ANY

grand cove
#

@tidal marlin I have mainly used Pyxel Edit and Aseprite, and so far I prefer Pyxel Edit mainly since I work with tiles a lot. I like the features it comes with for auto drawing on all tiles and so on.

#

And it's only like 9 bucks.

solemn quest
#

Could someone pls send me reference script of saving data for the player or any kind of data save?(to save progress and option settings)

zenith hill
#

hi guys, anyone knows whats a better way to create a game manager

#

as singleton or builder pattern?

tight shard
#

Unity 2D Collider, is there a version of OnTriggerExit but it triggers when only part of the collider is exiting

#

I need this cause I have a terrain (e.g. water) and I only want to make water sounds while the player is on top of it, this works when the player "enters", but when it exits, there's some delay because the player's collider is "bigger" and not a single dot, so that causes latency before the water walking sound changes back to the normal walking sound, if that makes sense

#

the only workaround is i have to create colliders surrounding the water as well, for the hard concrete floor

spring ledge
#

You could use OnTriggerStay and compare bounds yourself

tight shard
#

true ty

sharp storm
#

im trying to make my character move left and right but it says it has erros, does anyone know what those might be?

#

Me too buddy

spring ledge
#

@sharp storm It should tell you what errors it has :p

tight shard
#

You could use OnTriggerStay and compare bounds yourself
@spring ledge its harder than i thought (to make the footstep sounds in/out of the 2D terrain sound nice/responsive). I think the next solution I thought of is to make a "tiny" collider 1x1 pixel wide, store it as a child gameobject of the player, and when the player is moving right, it'll move this collider to the right, if left, then left, if up, then up, if that makes sense.

#

ah i can use OnTriggerStay and the direction

#

i'll try ontriggerstay with direction into account

sharp storm
#

i mean it does, i just dont understand what it means PepeCry

spring ledge
#

@sharp storm Well, step one would be to tell people here what it is

#

Crystal balls are rare these days

sharp storm
#

i suppose youre right

#

im very new to this

undone coral
#

Not a string, but there is a = where it shouldn't be. Double click the error, and check the code (or post it here).

spring ledge
#

you lack an opening { i nline 14

#

Also that if in line 26 needs another closing ) and probably and opening { after the closing) in the next line :p

sharp storm
#

Oooh I see

#

Thank you so much

fervent ermine
#

i am pretty new to unity and i am making a platformer and i need help getting a mario-like variable jumping system

#

ie you jump higher the longer you hold the button

woeful temple
#

maybe u could use rigidbody2d and check if the jump button is pressed and apply an upward force for every time they hold the button until its high enough

gentle mesa
#

ie you jump higher the longer you hold the button
@fervent ermine reduce the effect of gravity while the velocity is positive y and the jump is held

light elk
#

anyone using 9 slice in unity?

buoyant bolt
#

@sharp storm in your screenshot, your IF statements and your FixedUpdate functions, you're missing the { and your If statements are missing their closing bracket, they should look like this:

thin wraith
#

im trying to make my character move left and right but it says it has erros, does anyone know what those might be?
@sharp storm Friend

old kindle
#

@sharp storm missing { after void Start()

#

also after FixedUpdate()

fresh bridge
#

First question here.
Using boxcast for isGrounded, issue is that when jumping from under a platform I get grounded because of the collider, I've tried to make the boxcast smaller heightwise but to no avail.

Is it a good practice to make a empty child and have the boxcast on that instead?
Or should I disable the platforms as I am jumping (not falling) ?
Any tips would be great, ty

#

might be wrong channel, sorry if so

spring ledge
#

I've seen multiple tutorial use an empty gameobject to place the boxcast, don't see why you wouldn't. You could even just add some offset to your transform.position, but it's nicer to be able to place it in the editor

#

I wonder what the best way for a groundcheck is though. I've often seen the boxcast way, but it's kinda weird imo. You already have a physics engine which stops your object, so it feels like you should be able to use that

fresh bridge
#

Ok yeah, that is sort of what I want to be able to do, not fiddle with gizmo or debug.draw

spring ledge
#

Maybe can just set it on OnCollisionEnter or so

#

Would have to check orientation and such though, since else you'd still set ti to true if you hit your head on a platform instead of your feet

fresh bridge
#

I've tried so many approaches and always found issues I could not fix ๐Ÿ˜‰ Boxcast is what I've been looking for, cept for the platform thing atm. :)
I will try the empty and if it fails I will fix with OnCollisionEnter, I have time ๐Ÿ˜›

#

Thanks for the input!

tropic inlet
#

tbh, I wish I could like

[SerializeField]
private GameObject groundCheck;
private void Start(){
  groundCheck.GetComponent<Collider>().OnTriggerEnter += (col) => {
    //code
  }
}
#

setting the OnTriggerEnter of an object the script is not attached to

fresh bridge
#

That would've been ace

#

but there is a way to get another object is there not? ๐Ÿค” I am quite the noob at this so not sure

tropic inlet
#

u can get another object with, like GameObject.Find, or some RaycastHit but

#

i only know how to set the OnTriggerEnter/OnCollisionEnter of the object a script is currently attached to

spring ledge
#

OnTriggerEnter isn't a real even,t it's just a function called by Unity

fresh bridge
#

Ok yea

tropic inlet
#

I can prolly implement my own way of doing it

sharp storm
#

Thank you so much for helping guys

scarlet fractal
#

Hey I'm creating a Tower Defense game and now that I have a wave system with enemies prefabs I want to start placing towers. So for this I have to define where can the player place a tower/turret. I currently have a Grid that contains Tilemaps (Road, Decorations, Buildable terrain...)

Since this is a grid and I can actually see the cells in my Scene view would there be a way to do something with my BuildableTerrain Tilemap? Like getting every cells in this Tilemap or something?

tropic inlet
#

what is the name of the class

#

in the Move2D.cs file?

spring ledge
#

I mean, you have errors. Check your code in the editor and see what's wrong. If you "don't understand any of it", you probably will have to learn C#

tropic inlet
#

lol

#

u have to write code

#

in the .cs file

#

paste the code here

spring ledge
#

it says various things

tropic inlet
#

change "NewBehaviourScript" to "Move2d"

#

mb, lowercase d

#

fixed it in my edit

spring ledge
#

also don't put public stuff before the opening { of your class

#

๐Ÿ˜›

tropic inlet
#

do i change it?
it's text

#

u just replace the text as u would in a word document

#

basically,

#

ok, but i want u to

#

click moveSpeed

#

then hold alt and press the down arrow key

#

once

#

if u are using Visual Studio

spring ledge
#

Teaching them fancy shortcuts

tropic inlet
#

that should move that line down

#

now save the file

#

and see if it works in Unity

#

I have a feeling "horizontal" is supposed to be "Horizontal"

#

that's what that axis is called by default

#

of course, it's possible for people to change input settings

#

cant watch streams rn

spring ledge
#

Well once you remove all the errors, it should work. Does it stil show errors?

#

You still ahve to move the moveSpeed line

tropic inlet
#

yea it needs to be under the {

#

then remember to press ctrl + S

#

to save ur file

#

that asterik at the upper left means ur file is unsaved

#

like anyone who doesn't follow my religion

buoyant bolt
#

You need to move line 6 down the "public float movespeed"

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

public class Move2d : MonoBehaviour
{
    public float moveSpeed = 5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 movement = new Vector3(Input.GetAxis("horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }
}
#

this should work

#

notice this:

{
    public float moveSpeed = 5f;
#

Once you attach this to your object, and you press play

#

if your character does not move whenever you press your left and right arrow keys

#

you might need to change this line

 Vector3 movement = new Vector3(Input.GetAxis("horizontal"), 0f, 0f);

to

 Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
scarlet fractal
#

Anyone knows how I could have a turret system for my Tower Defence game? I already have a Grid that contains Tilemaps (one for the road, one for the buildable area...) but the only thing I can get so far is all the cells position within a tilemap but it also takes the empty ones any idea if there's a way to check if a tilemap cell is "empty" or another way to do this?

#

@still tendon you defined your condition in the Jump method. You're calling Jump() every time and checking if you're jumping that's kinda weird.
You should rather put your condition

if (Input.GetButtonDown("Jump")

where you actually call Jump (in your Update() I guess) and call Jump() inside it.
Then define Jump() to do a single action (just like what you'd expect from something that says Jump) as follow

void Jump()
{
  gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(, 0f, 5f,) ForceMode20.Impulse);
}```
scarlet fractal
#

@still tendon you didn't understand my point you should ask question if you're not sure you understood what I explained.
In your Update() put this

if (Input.GetButtonDown("Jump")
{
  Jump()
}```

and define your Jump method like this
```csharp
void Jump()
{
  gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
#

if you read the code above it makes sense because in your Update() which is literaly "Update every frame and see if something changed in the code" you call IF I press Jump button THEN you jump

#

you don't need to check if you're jumping when jumping this doesn't make any sense, do you understand my point?

#

Think of it as if you code for someone who don't know anything about computers

#

if I press Key.JumpKey then Jump() nothing more

#

make it english

#

like even if the person knows nothing she should still understand

#
void Update()
{
  if (Input.GetButtonDown("Jump")
  {
    Jump()
  }
}

void Jump()
{
  gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
#

@still tendon but you have to understand why I did it like this

#

did you understand? I can't make it simpler

#

which part don't you understand?

#

a method is defined like this:

access modifier (public or private) which you don't have here
void | return types (what your method will return, void is to create a method that just executes stuff without giving back data somewhere else in the code)
Jump is the method name, how you call it

tropic inlet
#

@still tendon
If you're new to C#

#

it's a good idea to learn how to make console applications first

scarlet fractal
#

yeah

tropic inlet
#

This shows how to create a new console app in Visual Studio 2019

#

Once you know how to do that

#

I recommend watching something like Brackey's series on C#

#

He's using Visual Studio Code rather than Visual Studio 2019, but it's ok.

#

Same language.

#

The reason for learning how to code via console apps is because they are lighter.
There are less distractions.
I use console apps whenever I just want to test some C# code

#

When you use Unity, it's expected that you know every topic in that list

#

But, of course, you could learn while using Unity if u want

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

public class PlayerMovement : MonoBehaviour{
     public flow movementSpeed;
     public Rigidbody2D rb;

     float mx; 

     private void update() {
     mx = Input.GetAxis("Horizontal");
     }

     private void FixedUpdate() {
         Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

         rb.velocity = movement;
     }
}     
#

doesnt show movement speed?

undone coral
#

public flow movementSpeed; is that supposed to be 'float'? :p

still tendon
#

oh yes

#

lol

undone coral
#

I don't see anything in the code that should cause issues. However, Unity doesn't update those if there's any errors (including in other scripts). So check the console for those, if any.

still tendon
spring ledge
#

There you go

#

You already have some other class PlayerMovement

still tendon
#

changed it to PlayerMover

#

and still

spring ledge
#

I mean, it's still called PlayerMovement there, have you renamed the script as well as change dthe class name in the script?

still tendon
#

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

public class PlayerMover : MonoBehaviour{
public float movementSpeed;
public Rigidbody2D rb;

 float mx; 

 private void update() {
 mx = Input.GetAxis("Horizontal");
 }

 private void FixedUpdate() {
     Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

     rb.velocity = movement;
 }

}

#

yes

spring ledge
#

And that file is PlayerMover.cs?

still tendon
#

yes

spring ledge
#

And you're sure Player Mover is what you have attached there, and not PlayerMovement?

#

Also, any remaining errors in the console?

still tendon
spring ledge
#

Yeah, so remove that and re-attachit

still tendon
#

remove what

spring ledge
#

the component thats the PlayerMovement script from your object

still tendon
#

ok hold up

#

i need to do smth

#

give me 3 mins

spring ledge
#

Also you probably don't want private for Update/FixedUpdate, and Update instead of update

still tendon
#

ok back

#

7:06

#

im following the tutorial

spring ledge
#

private may work, yeah

#

still Update,not update

still tendon
#

i changed it to Update

spring ledge
#

Well remove the PlayerMovement thing from your object and drag PlayerMover into it

spring ledge
#

?

#

you ahve a "Remove component" right there

still tendon
#

kk

#

works

#

ty

#

/test them game

spring ledge
#

Click on player and screenshot the inspector

spring ledge
#

Yes, drag your rigidbody to the Rigidbody slot on PlayerMovement

still tendon
#

kk

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

public class PlayerMover : MonoBehaviour{
     public float movementSpeed;
     public Rigidbody2D rb;

     public float jumpForce = 20f;
     public Transform feet;
     public LayerMask = groundLayers

     float mx; 

     private void Update() {
     mx = Input.GetAxis("Horizontal");

     if (Input.GetButtonDown("Jump") && IsGrounded ()) {
         Jump();
     }
     }

     private void FixedUpdate() {
         Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

         rb.velocity = movement;
     }

     void Jump() {
         Vector2 movement = new Vector2(rb.velocity.x, jumpForce);

         rb.velocity = movement;
     }

     public bool IsGrounded () {
         Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
         
         if (groundCheck.gameObject != null){
             return true;
         }
         return false;
     }
}     
spring ledge
#

that errors say (11,23)

#

That means Line 11

still tendon
#

fixed

#

sh

#

i was being dumb

#

also question

austere iron
#

@still tendon you dont have a variable name on line 11...

still tendon
#

why do my objects i put inside player keep disappearing

spring ledge
#

?

still tendon
#

hold up

#

like look

#

i set up the settings

#

and then it disappears

spring ledge
#

You're making them while the game is running

still tendon
#

oh right

spring ledge
#

click it

still tendon
#

sends me here

#

line 38

#

there is nothing wrong

spring ledge
#

probably groundCheck is null

round swallow
#

Hey I have a problem with the 2D TileMap Extras, it doesnt show me prefab brush anywhere

still tendon
round swallow
still tendon
#

dam

#

that game looks nice

spring ledge
#

@still tendon ". Null is returned if there are no colliders in the circle."

still tendon
#

the youtuber

#

he did the same as me

#

well i did the same as him

spring ledge
#

Then he did it wrong

round swallow
#

@still tendon do you mean mine?

still tendon
#

yea

#

@spring ledge so how do i fix

round swallow
#

Does anyone have an Idea where I can find it?

#

Thx

#

But they arent my assets

#

All I did was the shadow lol

spring ledge
#

you check if groundCheck is null

still tendon
#

oof but its a good game ur working on though

round swallow
#

Lol

#

All I have is movement

#

and animations

spring ledge
#

And no

#

I checked

still tendon
#

caps

spring ledge
#

That checks if groundCheck.gameObject is null, yes

#

And if groundCheck itself is null it'll error

#

๐Ÿ™‚

still tendon
#

so how would i fix

spring ledge
#

check if groundCheck isn't null

still tendon
#

how

#

i tried my self

spring ledge
#

What did you try

still tendon
#

by deleting return false;

spring ledge
#

So

#

I told you to check if groundCheck isn't null

#

How do you arrive at deleting return false; to accomplish that

still tendon
#

idk im fairly new

#

can u please tell me how

spring ledge
#

You're already checking if something isn't null

#

In fact, you said as much

still tendon
#

exactly so how do i check it again

#

it wont make sense

spring ledge
#

You don't

still tendon
#

so do i just delete the null

spring ledge
#

as I said, you're checking if groundCheck.gameObject is null, aka, the if gameObject field of the class that groundCheck is (in this case Collider2D) is null

#

so in that you're checking if groundCheck.gameObject isn't null

#

now how do you check if groundCheck isn't null?

still tendon
#

hm

#

i think i may know

#

let me see

#

actually

#

idk

#
     public bool IsGrounded () {
         
        if Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers) != null);
         
         if (groundCheck.gameObject != null) {
             return true;
         }
         return false;
     }
}     
#

i tried that

#

well it wont work

spring ledge
#

you have an if there, how do you modify that to check for groundCheck instead of groundCheck.gameObject

still tendon
#

remove game.object?

spring ledge
#

Yeah

still tendon
spring ledge
#

So what code do you ahve now

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

public class PlayerMover : MonoBehaviour{
     public float movementSpeed;
     public Rigidbody2D rb;

     public float jumpForce = 20f;
     public Transform feet;
     public LayerMask  groundLayers;

     float mx; 

     private void Update() {
     mx = Input.GetAxis("Horizontal");

     if (Input.GetButtonDown("Jump") && IsGrounded ()) {
         Jump();
     }
     }

     private void FixedUpdate() {
         Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

         rb.velocity = movement;
     }

     void Jump() {
         Vector2 movement = new Vector2(rb.velocity.x, jumpForce);

         rb.velocity = movement;
     }

     public bool IsGrounded () {
         
        Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers) != null);
         
         if (groundCheck != null) {
             return true;
         }
         return false;
     }
}     
spring ledge
#

Well you have to remove that != null) thing again you put in there

#

after the Collider2D groundCheck = [....] stuff

still tendon
#

sort of works

#

no erros

spring ledge
#

I find a lot of these tutorials that don't seem to explain the coding stuff much kinda weird I guess

#

Makes it seem like people just think of it like some weird incantation

still tendon
#

no errors but it doesnt jump ;/

spring ledge
#

In Update() put a Debug.Log(IsGrounded()); and check what it outputs in the console while you're running the game

still tendon
#

ok

#

private void Update(Debug.Log(IsGrounded())) {

#

like that?

spring ledge
#

no, inside the function

#

It's ac ommand

still tendon
#

ok

spring ledge
#

It outputs whatever IsGrounded() returns to the console

still tendon
#

private void Update() {
Debug.Log(IsGrounded());
mx = Input.GetAxis("Horizontal");

spring ledge
#

Hmm show your game as thats printing out

spring ledge
#

Whats feet, and whats groundLayers set to too

#

Also whats with the mouse gestures ๐Ÿ˜‚

still tendon
#

its going up

#

omg

spring ledge
#

Whats going up

#

Yeah but like

#

go to sceneview

#

And select feet on the left

still tendon
#

ok

spring ledge
#

and if you click player?

still tendon
spring ledge
#

Also pause the game if it isn't

#

Or rahter, stop it

still tendon
#

it is

#

i stopped it

spring ledge
#

click the feet thing again and press ... W I think it was

#

should have a gizmo to move that around

still tendon
spring ledge
#

thats with feet select?

#

Move it down slightly (with the green one)

hushed lynx
#

What would be a good / clever way to make a character "skin" selection?

still tendon
spring ledge
#

Not that far really

hushed lynx
#

I was thinking about just changing the position of a sprite to fit the character but I'm sure they're would be a smarter way.

spring ledge
#

Just a bit , and not to the side ๐Ÿ˜›

still tendon
#

ok

spring ledge
#

Still a bit too far downjust a tiny bit lower than it was before

#

Then click on Player and show the PlayerMovement thing in the inspector

still tendon
#

ok

spring ledge
#

Yeah, sorta like that should work

still tendon
spring ledge
#

It's just since the radius for it is .5 and your player is 1. So a .5 radius might not find the ground because it ends right as your player ends, doesn't intersect with the ground. So by moving it down slightly thats better

#

No, like, the script hitng

#

Where you set feet and groundLayers an dsuch

still tendon
spring ledge
#

That seems right. Click ground and make sure it's on the Ground layer

still tendon
#

it is

#

works

spring ledge
#

nice

#

So probably was just htat oyu had to move feet down a little

still tendon
#

YE

#

but

#

i need to make proper characters now

#

because with a blob if the feet are on one side and it flips then i cant jump

still tendon
#

Can I have the same line of code in two different pages? I need to trigger an animation when I am grounded but my isGrounded is on another page.

tropic inlet
#

GetComponent<otherScriptName>().isGrounded

#

GetComponent can access other scripts attached to your object

still tendon
#

Thank you

still tendon
#

@tropic inlet I am getting the following error from what you told me to do "Assets\Scripts\PlayerController.cs(26,40): error CS0122: 'Controller.m_Grounded' is inaccessible due to its protection level" Any ideas?

plush coyote
#

There should be a public property like isGrounded or something

#

if not, you could always go into the code and change m_Grounded to public

still tendon
#

Works perfect, thanks

stuck urchin
#

Anyone know how to fix this, the problem is the collision is not working. Like the debug.Log statements does not show in console and the hitpoints variable doesn't go down when collision is made. And yes my enemy object has a box collider.

upper wedge
#

I'm trying to make a simple project where the ball bounces and when it hits a wall the background color changes

#

I have the ball bouncing off the walls I just dont know how to add the collision to change the background color

#

This is where I am at

#

I tried adding GetComponent<Renderer>().material.SetColor("_Color", Color.red); when the ball collides with the walls, but all it does is change the ball color and not the background

still tendon
hollow crown
#

That is visual studio?

#

They need to properly configure it

mystic void
#

I'm making a knockback mechanic for a game which knocks back the player based on its x position relative to the enemy, if the player is to the left of the enemy the knockback direction will be left and vice versa. To check this I am transform.position.x for both characters. The issue with this is that their original value is not the same. The original x position for an enemy could be -20 for the player. How do I solve this?

tropic inlet
#

wat

#

wym by original value

mystic void
#

if you take both of the game objects and put their x position at 0, they won't end up at the same position in the scene

tropic inlet
#

damn

#

if gameobjects have the same location, they should be at the same spot as far as I know

#

could it be that

#

ur colliders are positioned incorrectly?

#

like

#

maybe the collider is distant from ur gameobject's center due to some offset

mystic void
#

their origin points aren't at the same location

#

according to the inspector for these two game objects, their position on the x axis are both at 0

#

the distance between them isn't 0 which is what causes the issue with the knockbacks

spring ledge
#

How did you manage that ๐Ÿค”

#

They're like 7 units apart horizontally despite both being at 0?

mystic void
#

I suppose their position might be relative to where they were placed

spring ledge
#

shouldn't be

#

Do they have a parent that moves?

#

Then 0 would be relative to parent

#

At least in the editor

mystic void
#

That might be it, they donโ€™t have the same parent

spring ledge
#

Wheres is the parent at?

#

And how do you calculate the knockback

#

transform.position.x should give you world coordinates, not relative to parent

#

The editor shows relative to parent though when you have it selected

mystic void
#

Will have to check when I get home

#

Thanks for the help btw

scarlet fractal
#

Can someone help me getting every non empty tile in a tilemap (and only in the tilemap) please?
Getting every green cells only (Tilemap Collider 2D) would be cool
I'm trying to check if a tile is part of a tilemap and if it's not empty when I click on it.
Basically what I want is to have a buildable tilemap and build something whenever you click in any of the tiles in this particular tilemap. I tried lot of different stuff but I really can't get anything good

spring ledge
#

That sounds like a terrible way to do that ๐Ÿ˜„

#

You should somehow get mouse position and calculate the tile clicked from that

#

Then you can access that specific tile directly

#

Instead o fhaving to build a gigantic list

scarlet fractal
#

Well yeah I'm really lost here I've been searching since yesterday.
For now I have the mouse position when clicking and I can check if the click position is within the tilemap

#

but it's an area so it also takes other tilemaps and all

spring ledge
#

Well I'm not sure if your setup is

scarlet fractal
#
if (Input.GetMouseButtonDown(0))
{
Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pz.z = 0;

Vector3Int cellPosition = myTilemap.WorldToCell(pz)

foreach (var VARIABLE2 in myTilemap.cellBounds.allPositionsWithin)
{
if (cellPosition == VARIABLE2)
{
transform.position = myTilemap.GetCellCenterWorld(cellPosition);                
}
}
}
spring ledge
scarlet fractal
#

for now cellPosition is my mouse click position converted to the tilemap
then I check if my click is within the tilemap bounds (foreach) and if click position == a cell within the bounds I set my tower here

#

the thing is that the foreach is really bad

spring ledge
#

Well good that you realize that it's bad

scarlet fractal
spring ledge
#

What do you mean with "build everywhere between"

scarlet fractal
#

it seems to be working.. I can't be believe it's that simple

#

I found this before but got caught in so much things that I forgot about this method

#

yeah sorry what I meant is moving. whenever I click on one of the tile in the tilemap it moves the GameObject the script is attached to$

#

well thank you very much I was searching since yesterday morning I feel so dumb

#

can't believe I got stuck so long just for this but again thanks a lot!

brisk hemlock
#

I have a question, i am making a 2D game, but when i move the object and there are colliders on both objects and in the code if i just have void OnTriggerEnter2D it wont work. Can you help me with this?

#

this is the exact code private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("colided with lava");
Destroy(collision.gameObject);
}

clever sky
#

Is there a reason it's a private void?

#

What happens if you mark it public?

tropic inlet
#

private means it can't be accessed from beyond the definition of the class

#

For functions like Update and Start, I just make them private because there is no reason for any other script to access it

still tendon
#

@clever sky Public fields will be displayed in the editor and can be edited (like this)

#

Thats the way i can explain it

tropic inlet
#

public fields*

still tendon
#

same thing

tropic inlet
#

functions are a bit different

still tendon
#

yes i know

tropic inlet
#

public functions will be visible to the animation event thing

clever sky
#

But wouldn't OnCollisionEnter2D() need to be a public method?

still tendon
#

nope.

clever sky
#

welp

still tendon
clever sky
#

@brisk hemlock how "Doesn't it work"?

tropic inlet
#

u can mix them @ Timi

#

you can reserve cinematic ones for, like, special enemies or

#

highly skill-based tactics employed by the player

#

depends on the mood of ur game and how frequently they happen, rly

#

also how long they take

silent bay
#

hey i have issues with getting my character go of the map when I jump, i have created a ontheground variable ans I putted this line of code in the void updat thing if (Input.GetKeyDown("space") &&ontheground) I don't understand please help

fiery oar
#

hi

#

i need help

how would i move 2d sprite in upward direction according to the sprite using rigidbody2d

clever sky
#

@silent bay do you remember to update ontheground?

silent bay
#

what do you mean?

#

@clever sky

clever sky
#

I don't understand you question maybe

silent bay
#

ok let me put everything

clever sky
#

Are you trying to make a jump function

silent bay
#

no

fiery oar
#

no
Are you trying to make a jump function
@clever sky

silent bay
#

I want to make a function that makes my player not fly around with spamming space

clever sky
#

oh

silent bay
#

oh

fiery oar
#

i want the 2d sprite to go to upward direction with respect to its rotation

any help

silent bay
#

``

clever sky
#

in that case

silent bay
#

wtf it's getting delelted

grand cove
#

@silent bay use hatebin or something

#

You can't post a whole files content into a text message here

silent bay
#

ok lol

clever sky
#

@silent bay make it so you do like

if (Input.GetKeyDown("space") &&ontheground) 
{
  ontheground = false;
  // rest of the code here
}
fiery oar
#

i want the 2d sprite to go to upward direction with respect to its rotation

any help
@fiery oar anybody knows how

silent bay
#

I just did it

grand cove
#

...just rotate the game object? @fiery oar

#

what do you mean with respect to it's rotation?

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



public class charactercontroller : MonoBehaviour
{

    public Rigidbody2D rb;
    public float vitesse;
    public float sautmax;
    private bool ontheground = false;

    void Start()
    {
        rb.velocity += new Vector2(vitesse, 0);
    }


   
    void Update()
    {
        if (Input.GetKeyDown("space") &&ontheground){
            Jump();
        }
   
    }

    void OncollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("ground"))
        {
            ontheground = true;
        }
    }

    void OncollisionExite2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("ground"))
        {
            ontheground = false;
        }
    }

    void Jump()
    {
        rb.velocity += new Vector2(0, sautmax);
    }

    private string GetDebuggerDisplay()
    {
        return ToString();
    }
}
#

that's my code

spring ledge
#

Meaning they want it to go "up" on the local up direction, not the global up direction

#

Presumably

fiery oar
#

what do you mean with respect to it's rotation?
@grand cove i want it like in 3d we use transform.forward so like that how to use it in 2d

#

Meaning they want it to go "up" on the local up direction, not the global up direction
@spring ledge yeh but how to do

clever sky
#

what if you fix this OncollisionExite2D to OncollisionExit2D?

spring ledge
#

@fiery oar What does transform.forward give you?

clever sky
#

(there's an extra e in your version)

silent bay
#

oh ye

#

maybe

fiery oar
#

@fiery oar What does transform.forward give you?
@spring ledge its for vector3 so it wont work

#

i want it for vector2

spring ledge
#

@fiery oar What does it give you? Abstractly, not the value

silent bay
#

nope

spring ledge
#

@fiery oar Btw, 2d games still use vector3 for gameobjects

grand cove
#

you can just convert the vector 3 to a vector 2...

silent bay
#

but i've tryed with and without and the probleme is &&ontheground

fiery oar
#

you can just convert the vector 3 to a vector 2...
@grand cove how to convert it

grand cove
#

just put (Vector2) in front of the vector 3 value

silent bay
#

is there a other function maybe?

grand cove
#

vector 2 is literally the same thing as a vector 3 but it has 1 less value <.<;

clever sky
#

@silent bay try and Debug.Log("Jumped") in you collision code to check if it even gets called?

silent bay
#

ok

#

i maybe have a ide

fiery oar
#
    void Update()
    {
        if (Input.GetKey("left"))
        {
            if (Input.GetKey("right"))
            {
                shipRB.velocity = new Vector2();
                Debug.Log("working");
            }
        }  
    }

its my update loop can you tell how to do

grand cove
#

oh goodness, you need to learn how to code c# before starting to make a game, bruh

fiery oar
#

ok

#

oh goodness, you need to learn how to code c# before starting to make a game, bruh
@grand cove but whats wrong in these code

grand cove
#

why would you press both left and right at the same time?

silent bay
#

oups srry

#

i didn't see

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



public class charactercontroller : MonoBehaviour
{

    public Rigidbody2D rb;
    public float vitesse;
    public float sautmax;
    private bool ontheground = false;

    void Start()
    {
        rb.velocity += new Vector2(vitesse, 0);
    }


   
    void Update()
    {
        if (Input.GetKeyDown("space") &&ontheground){
            Jump();
        }
   
    }

    void OncollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("ground"))
        {
            ontheground = true;
        }
    }

    void OncollisionExit2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("ground"))
        {
            ontheground = false;
            Debug.Log("Jumped!!")
        }
    }

    void Jump()
    {
        rb.velocity += new Vector2(0, sautmax);
    }

    private string GetDebuggerDisplay()
    {
        return ToString();
    }
}
 
fiery oar
#

i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction

silent bay
#

thks man

clever sky
#

then you can at least see if it stops colliding with the ground

fiery oar
#

i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction
@fiery oar i want it to be like the minecraft boat controls

#

any help

clever sky
#

i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction
@fiery oar something like

if(Input.GetKey("left") && Input.GetKey("right"))
{
  // code for moving forward
} else if (Input.GetKey("right")) {
  // code for rating
} else if (Input.GetKey("left")) {
  // code for rating the other direction
}

Or are you asking for the code for moving "forward"?

fiery oar
#

yeah but instead i want to go upwards

silent bay
clever sky
#

fixit ๐Ÿ˜›

fiery oar
#
    void Update()
    {
        if (Input.GetKey("left"))
        {
            if (Input.GetKey("right"))
            {
                shipRB.velocity = new Vector2(what to write here);
                Debug.Log("working");
            }
        }  
    }

clever sky
#

I rarely code in languages with semicolons

grand cove
#

shipRB.velocity = transform.up; @fiery oar

silver walrus
#

Hi! I was trying to get a Text (TextMeshPro) show up for a few seconds in my scene as soon as I touch it's collider. However, it doesn't seem to be working, can I get some help?Thanks in advance

grand cove
#

but 2D is different from 3D, there is not forward @fiery oar you have to calculate that your self or rotate the game object and keep using transform.up as "forward"

fiery oar
#

it works

#

i want no gravity in rigidbody2d so it moves in the direction for ever

how can i make it to come at rest in the script

#
public class Ship_Controller : MonoBehaviour
{
    public Rigidbody2D shipRB;
    public float speed = 1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("left"))
        {
            if (Input.GetKey("right"))
            {
                shipRB.velocity = transform.up * speed;
                Debug.Log("working");
            }
        }  
    }
}
#

its my whole script

clever sky
#

I believe you can remove gravity from the inspector

silent bay
#

@clever sky so i fixed it but it doesn't fucking work

still tendon
#

How do i add gravity and movement to my game

grand cove
clever sky
#

@clever sky so i fixed it but it doesn't fucking work
@silent bay but does it print?

silent bay
#

so I think i'm just gonna rewrite everything

spring ledge
#

2d has forward btw

#

It just points into the screen

#

๐Ÿ˜„

fiery oar
#

i know

spring ledge
#

Thats why I asked you what forward returns btw

silent bay
#

heu

fiery oar
#

as z axis is towards the screen

silent bay
#

Nope

#

i don't think so lol

still tendon
#

How do i add gravity and movement to my game

clever sky
#

then the collision doesn't exit

spring ledge
#

Forward returns the positive Z-axis. What has 2D? x, and y. So we do'nt need forward. Whats up in 2d? y. Whats the transform for up?

fiery oar
#

i have my issue fixed

clever sky
#

@spring ledge isn't it just .up?

fiery oar
#

yes

silent bay
#

do you think the problem is from "collision2D"

grand cove
#

How do i add gravity and movement to my game
@still tendon Read up on rigid body and use the unity beginner tutorials.

clever sky
#

The collision doesn't trigger

silent bay
#

oh

clever sky
#

I personally don't know how to trigger collision, I just know how to print statements my way to victory ๐Ÿ˜„

spring ledge
#

did you spell it OnCollisionEnter now

#

or is it still OncollisionEnter

silent bay
#

gonna check

clever sky
#

From the code pasted earlier, it was OncollisionEnter2D

silent bay
#

OMG

#

SO STUPID

fiery oar
#
public class Ship_Controller : MonoBehaviour
{
    public Rigidbody2D shipRB;
    public float speed = 1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("left"))
        {
            if (Input.GetKey("right"))
            {
                shipRB.velocity = transform.up * speed;
                Debug.Log("working");
            }
        }  
    }
}

here i want my gravity to be off in the inspector by doing so the object continues to travel in the direction forever so how to gradually decrease the velocity

silent bay
#

thanks

#

man

#

when i will be good at dev I promess i will help a noob lmao

fiery oar
#
public class Ship_Controller : MonoBehaviour
{
    public Rigidbody2D shipRB;
    public float speed = 1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("left"))
        {
            if (Input.GetKey("right"))
            {
                shipRB.velocity = transform.up * speed;
                Debug.Log("working");
            }
        }  
    }
}

here i want my gravity to be off in the inspector by doing so the object continues to travel in the direction forever so how to gradually decrease the velocity

or the second way to say is how to implement gravity in code

grand cove
#

Christ, people don't even do basic tutorials before they start blasting questions here any more, I'm off.

clever sky
#

@spring ledge does gameobjects just casually have collisions for free? ๐Ÿ˜ฎ

spring ledge
#

Only if you put in colliders?

clever sky
#

That makes sense

fiery oar
#

Christ, people don't even do basic tutorials before they start blasting questions here any more, I'm off.
@grand cove i have basic knowledge but i want the efficient code that's why im asking

#

my issue solved

spring ledge
#

You're literally asking how to dampen velocity over time. I'm not sure that counts as basic knowledge ๐Ÿ˜„

grand cove
#

If you know the basics, then you should know what transform does and how to use it to "fake" gravity.

fiery oar
#

i instead did increase linear drag

#

it worked for me so no need to write a script

still tendon
#

So I made a platform collider so that you could go through a ceiling and floor, but if you go through the floor, it does not stop. I want to turn it off right after they go through it.

#

Any help?

scarlet fractal
#

@still tendon if I understand what you say you could use the OnTriggerEnter2D method (requires a Rigibody and a Collider 2D on your player)

#

then you could use the collider that's given in parameters and use .Compare("yourPlayerTag") as a condition and inside this if put your .enable = false or something

still tendon
#

On what event would I make it false though @scarlet fractal

scarlet fractal
#

whatever you're using to make your collision turn it off

still tendon
#

okay thanks

spring ledge
#

Do you mean Mathf.Abs(Input.GetAxis("Horizontal"))? Because Mathf.Abs("Horizontal") literally just gives it the string "Horizontal" when it wants a float

tame lava
#

Is there a way to select all **particles **in a certain radius? The same way as OverlapCircleAll finds all colliders.

tame lava
#

ans:

var droplets = new ParticleSystem.Particle[rain.particleCount];
var num = rain.GetParticles(droplets);
for (var i=0; i<num; i++)
{
    if (Vector2.Distance(droplets[i].position, rb.position + rb.centerOfMass) <= radius)
    {
        droplets[i].remainingLifetime = 0;
    }
}
rain.SetParticles(droplets, num);
spring ledge
#

@tame lava Use DistanceSquared and square your radius before comparing it

#

(Sort of depends on how many particles you have and how often you do that for it to matter though :P)

slate token
#

i thought about having the parent having a rigidbody and a composite collider, but i don't know how i would go about checking collision for individual blocks (as they can be damaged individually)

tame lava
#

@spring ledge about 300 particles, every frame. Is DistanceSquared faster or something?

#

Oh, makes sense, it just doesn't need to take a square root every time.

spring ledge
#

Yeah

tame lava
#

Idk if it's me being dumb but it

Cannot resolve symbol 'DistanceSquared'
var distSquared = Vector2.DistanceSquared(droplets[i].position, rb.position + rb.centerOfMass);

#

Vector2.cs doesn't have it.

spring ledge
#

๐Ÿค”

spring ledge
#

@tame lava Not sure why they don't have that, but you can do distSquared = (droplets[i].position - (rb.position + rb.centerOfMass)).sqrMagnitude instead

#

Oddly the sqrMagnitude docs even note that its faster than magnitude, and Distance says it's the same as (a-b).magnitude. So no clue why they decided to have no DistanceSquared

scarlet fractal
#

Hey I have a turret GameObject with this script attached that strikes every 2s and slows every enemy GameObject within its radius (Tower Defense game). My only issue is that when an enemy exits the slow radius his speed goes back to normal but almost of the enemies have their speed reduce once after it.
Anyone knows what I could do? Or at least see my OverlapCircleAll in my Scene to see if it match my turret Circle Collider 2D?

public class TurretTest : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(SlowAttack());
    }

    IEnumerator SlowAttack()
    {
        yield return new WaitForSeconds(2);
        Collider2D [] colliders = Physics2D.OverlapCircleAll(transform.position, 7f);
        if(colliders.Length > 0)
        {
            foreach (var VARIABLE in colliders)
            {
                if (VARIABLE.CompareTag("Enemy"))
                {
                    Debug.Log(VARIABLE.name);
                    SlowEnemy(VARIABLE);
                }
                
            }
        }

        StartCoroutine(SlowAttack());
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        Debug.Log(other.name + "EXITED RADIUS");
        var script = other.GetComponent<EnemyMovement>();
        script.Speed = script._defaultSpeed;
    }

    void SlowEnemy(Collider2D other)
    {
        var script = other.GetComponent<EnemyMovement>();
        if (script.Speed > 2)
        {
            script.Speed = script.Speed - 0.5f;
        }
    }
}```
tame lava
#

@spring ledge thanks!

spring ledge
#

@scarlet fractal Thats an odd way to use coroutines? why not just while true it

#

@scarlet fractal Also not sure what you mean. Enemies stay slowed?

heavy token
#

@scarlet fractal that system is gonna break once you have more then 1 slow effect, because the Turret removes all slows and not just it's own. I would apply slows as a Debuff, but that would be a little to advanced for you I think.

still tendon
#

someone wanna created a game 2D

spring ledge
#

True

scarlet fractal
#

@heavy token yeah you're right didn't think of this, I think I'm gonna search for a debuff tutorial then.
Maybe I could update an isSlowed bool on my enemy so that when it's false my enemy starts recovering his speed bit by bit instead of resetting to the default value so that if he enters in another slow turret's radius it goes back to isSlowed?

@spring ledge wdym while? I used OnTriggerStay2D() before but it ran my slow code every time.

spring ledge
#
    IEnumerator SlowAttack()
    {
        while (true) {
            yield return new WaitForSeconds(2);
            Collider2D [] colliders = Physics2D.OverlapCircleAll(transform.position, 7f);
            if(colliders.Length > 0)
            {
                foreach (var VARIABLE in colliders)
                {
                    if (VARIABLE.CompareTag("Enemy"))
                    {
                        Debug.Log(VARIABLE.name);
                        SlowEnemy(VARIABLE);
                    }        
                }
            }
        }
    }```
scarlet fractal
#

I don't really understand how this will change? Actually my slow is executed 1 more time than it should so would while(true) change this/what would it change?

spring ledge
#

It just mean you're not constantly making a new coroutine if you can keep one running ๐Ÿ˜›

scarlet fractal
#

so this will only slow my enemy once? what I want is a turret that hit the ground and slow enemies in its radius a bit every time it hits the ground while they're in the turret's radius

#

maybe I could also change the behavior to make just slow every enemy inside it to a fixed value and then whenever they get out they progressively get their speed back

heavy token
#

@scarlet fractal he means that instead of calling your Coroutine again at the end of your Coroutine you could have it in an endless loop instead.

scarlet fractal
#

oh that's just better in term of memory usage? @spring ledge I'm not thinking of performance for now but thanks this should be way better performance wise

heavy token
#

@scarlet fractal a debuff class would have a baseDuration, timer and enemy it is affecting. If it's a slow debuff it would have a slowAmount value, when it is applied reduce the speed of the enemy by X amount. When the duration reaches 0 add X to the enemies speed again.

#

But you would also have to learn about Inheritance

scarlet fractal
#

So like if the enemy is in the radius he will be slowed by 5 for 3 seconds but only once if he's already slowed

#

and when isSlowed is false he progressively gains his speed back

still tendon
#

uh hi i need help in unity2d.
so i need to my player rotate towards nearest enemy, and i dont know how...
can anyone help?

sweet swan
#

@still tendon

Vector2 dir = target.position - rb.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + 90f;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
```here's what i use for 2d rotations
round raven
#

Quick dummy question. Haven't worked in 2d in a while. I know in the past re-using animations with different sprites wasn't possible. Or at least not simple. But a while ago I saw a few presentations about sprite libraries that suggested they might be able to accomplish it. Am I on the right track?

sweet swan
round raven
#

Thanks, I'll give this a look and see how it goes

glad plume
#

2D render pipeline with the new experimental 2d lights. Is it possible to get the value of illumination of an object somehow? Or better yet. Add a component to the light that can check if the player is hit by the light.

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

public class Scripts : MonoBehaviour
{
    
    public float MovementSpeed = 1;
    public float JumpForce = 1;

    private Rigidbody2D _rigidbody;


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

   
    void Update()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;


    if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001)
    {
            _rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
    }


    }


}
#

Any help?

scarlet fractal
#

@still tendon you should learn C# before Unity. NullReference means the reference you gave is null which means nothing. In your error it's written Scripts.Update() so this happens in your Update() method. The problem probably comes from _rigidbody. Did you add a Rigidbody in your inspector?

#

Also you can debug yourself: is this problem happening on start or when I press the Jump key? If it happens when you press your Jump key then the problem comes from something inside your Jump key condition.

still tendon
#

lol

#

Learn C#

#

Anyone decent at C# would see it was missing a f at the end

scarlet fractal
#

Your error is NullReferenceException

#

also it says it's line 28

still tendon
#

Doesn't matter, I'll just change the 0,001 to 0,001f

#

And it works

#

lol

spring ledge
#

An f there doesn't matter though ๐Ÿค”

vocal condor
#

But the null reference exception definitely does ๐Ÿ˜‰

#

Guessing you do not have a Rigidbody2D attached to your GameObject..

still tendon
#

I legit changed it to an f

#

and it worked

vocal condor
#

"it worked" isn't relative to the error you posted..

still tendon
#

Fixed it

#

By adding

#

an f behind 0.001

spring ledge
#

fmatters on assignment. For example float abc = 0.3; this would need the f. Because without any addition that 0.3 is a double, not a float. You're assigning it to a float, so you'd potentially get wrong data as a float is less precise than a double. Thats why it needs you to denote that you're putting a float by adding f. Comparing double to float works without f's

still tendon
#

Why would you argue, when it works lmao

spring ledge
#

You sure you didn't assign a rigidbody during those tests or something ๐Ÿ˜›

#

Lets do it the science way

#

remove the f again

#

Does it break?

still tendon
#

Yes

vocal condor
#

Because we aren't.. we're explaining your error.. not feeding self justifications ๐Ÿคทโ€โ™‚๏ธ

still tendon
#

I've done it 5 times

#

Didn't ask for an explanation, but thanks.

spring ledge
#

Unlikely, but sure

vocal condor
#

Well.. I see the null reference exception error and.. "Any help'.. so not sure what you're asking if not for explanation support because it's a pretty simple error..

still tendon
#

{
cout << "Didn't ask";
//end of chit-chat
}

spring ledge
#

Works for me with or without the f

#

So you're doing something else wrong

vocal condor
#

Same but whatever ๐Ÿคทโ€โ™‚๏ธ

spring ledge
#

Also you should use std::cout; there. using namespace std; is incredibly bad practice

#

๐Ÿ˜›

still tendon
#

Couldn't care less, using namespace std; is way faster

#

and much more efficient

#

๐Ÿ˜›

scarlet fractal
#

That's what I told him

tropic inlet
#
using std::cout;
#

For beginners, using namespace std; is fine. If they don't even understand what a variable, function or scope is, it's unlikely that they are writing any large projects that are vulnerable to name clashes.

#

When they start becoming intermediate, and they start writing larger programs, they'll begin to see the benefits of being explicit due to how the creators of the standard library dumped so much into one namespace.

#

Couldn't care less,
You are the first person in ages

#

that has used this phrase correctly

#

Everyone else says "I could care less", which is the opposite of what they intended to convey

still tendon
#

I guess Norwegian schools are pretty good then.

still tendon
#

hello, could someone help me?

#

I am producing a project where I need to throw objects and after a while they self-destruct, but all very quickly, since I send teleport. I can normally destroy the first prefab that the player shoots, but the next one is intact, being deleted only from the list and not being destroyed, I have been trying to solve this problem for a long time and I am new to programming.

My attempt:

{
    yield return new WaitForSeconds(timerRange);
    rb2b.constraints = RigidbodyConstraints2D.FreezePosition;
    yield return new WaitForSeconds(timerRange);
    Destroy(playerController.projectiles[playerController.projectiles.Count - 1]);
    playerController.projectiles.RemoveAt(playerController.projectiles.Count - 1);
}```

I can't use "Destroy (gameObject);" since he gives the following error and I need the player to teleport as soon as possible: "The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object."

Sorry for my bad English, I'm not very fluent.
real pilot
#

Anybody got tips for optimizing performance with large destructible physics enabled tilemaps?

tropic inlet
#
GetComponent<Rigidbody2D>().AddForce(Vector2.up * 100.0f);

jump script done

#

i accept paypal

elfin belfry
#

do normal charactercontrollers work on sprites?

tropic inlet
#

u can create a gameobject, give it a sprite render and a character controller

sour bone
#

Please Help! I'm trying to make a camera like Forager. I've been reading documentation and I am still confused.

    {
        viewPortSize = (cam.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)) - cam.ScreenToWorldPoint(Vector2.zero)) * viewPortFactor;

        distance = player.position - transform.position;
        if (Mathf.Abs(distance.x) > viewPortSize.x / 2)
        {
            targetPosition.x - player.position.x - (viewPortSize.x / 2 * Mathf.Sign(distance.x));
        }
        if (Mathf.Abs(distance.y) > viewPortSize.y / 2)
        {
            targetPosition.y - player.position.y - (viewPortSize.y / 2 * Mathf.Sign(distance.y));
        }

        transform.position = Vector3.SmoothDamp(transform.position, targetPosition - new Vector3(0, 0, 10), ref currentVelocity, followDuration, maximumFollowSpeed);
    }```

**targetPosition.x - player.position.x - (viewPortSize.x / 2 * Mathf.Sign(distance.x));** and
**targetPosition.y - player.position.y - (viewPortSize.y / 2 * Mathf.Sign(distance.y));** have red squiggly lines under it. I am using code from 2019, could it be outdated?

EDIT: Nevermind, the "-" right after **targetPosition.x** and **targetPosition.y**, was supposed to be an equals ![facepalm](https://cdn.discordapp.com/emojis/456770802667356160.webp?size=128 "facepalm")
keen siren
#

Guys anyone know of a tutorial about GetComponent for Tilemaps?

#

I've found the reference.

#

Is there a way to assign a script to a tile or tile map. Should you create a likewise grid of tiles by returning TileMap.cellBounds and simulating properties?

#

Wait, if I create a huge array using TileMap properties from the TileMap I can calculate the exits from each tile

#

Then pathfinding is easy.

spring ledge
#

๐Ÿค”

#

I mean, it would work

remote moth
#

How can i get all objects in a spectify radius of a object?

vocal condor
#

Circle cast or sphere cast if your objects have colliders.

remote moth
#

Circle cast or sphere cast if your objects have colliders.
@vocal condor thx, but i've already figured it out myself

#

how can i create a object by c# script?

vocal condor
#

You can create using instantiate or keyword new.

remote moth
#

new GameObject?

sudden cedar
#

i have a problem, why i have this All compiler errors have to be fixed before you can enter playmode! UnityEditor.SceneView:ShowCompileErrorNotification()

vocal condor
#

@sudden cedar fix all of your compiler errors.

sudden cedar
#

think

vocal condor
#

Fix them from top to bottom..

remote moth
#

how can i give this gameobject a texture by script?

vocal condor
#

.... You need to start searching for tutorials online...

remote moth
#

ok .-.

vocal condor
#

These are pretty basic questions..

#

A renderer allows an object to be displayed.

#

There are many types.

#

They are all components.

sudden cedar
#

what am i supposed to do with the code from the link you sent me i don't understand

vocal condor
#

It wasn't for you.. you need to fix your errors.

#

Fix them from top to bottom..
@vocal condor

sudden cedar
#

How

#

but i have nothing

vocal condor
#

Scroll up and read the first error. I'm assuming you kept trying to play the application and unintentionally hid the original error.

sudden cedar
#

i have nothing

vocal condor
#

I see six errors being reported.

sudden cedar
vocal condor
#

Double click and check the details pane below.

#

Clear the console as well.

#

Is this a new project?

sudden cedar
#

nop i crated 2 week ago

vocal condor
#

Clear the console as well.
@vocal condor

#

And show us what you now see.

sudden cedar
#

i double click but noting

vocal condor
#

Not entirely sure, it's not a script error (especially related to 2D), more like a setup error. Post your question in #๐Ÿ’ปโ”ƒunity-talk.. Not much folks will be able to give you the exact answer but there are others on the net with your problem and the solutions aren't too solid..

sudden cedar
#

ok think

still tendon
#

@jagged belfry @jagged belfry @jagged belfry is a good programmer ๐Ÿ˜

#

@jagged belfry yo bro

#

@jagged belfry Do you watch any anime

#

๐Ÿ˜น

vocal condor
#

Not related to coding <@&502884371011731486> @still tendon

timid plover
#

!warn @still tendon Don't spam ping people.

barren orbitBOT
#

dynoSuccess Pixie Sprite#7791 has been warned.

timid plover
#

!mute @still tendon 1440

barren orbitBOT
#

dynoSuccess Pixie Sprite#7791 was muted

timid plover
#

Thanks @vocal condor !

low obsidian
#

Does anyone know how to make 2d ragdoll physics for a stickman?

#

I just started Unity like this week and I want to make a 2d ragdoll game so i would appreciate any help

remote moth
#

How can I make the object go in the direction he is facing?

scarlet fractal
#

@remote moth I think you could use Quartenion. Maybe try to Debug.Log Quartenion.Identity to see where he's facing

#

Hey I currently have a script that spawns a GameObject where I click but I can spawn an infinite amount of this GameObject on top of each other, is there a way to check if there's already a GameObject at my mouse position? I don't think creating a List of every GameObject I spawned would be a good practice performance wise.

remote moth
#

Hey I currently have a script that spawns a GameObject where I click but I can spawn an infinite amount of this GameObject on top of each other, is there a way to check if there's already a GameObject at my mouse position? I don't think creating a List of every GameObject I spawned would be a good practice performance wise.
@scarlet fractal you want that it create one object wenn you click?

plush coyote
#

You could raycast to the mouse or something simple like that

scarlet fractal
#

No I already have this. My issue is that I only want to create one per position I don't want to have GameObjects on top of each other

plush coyote
#

If it is a grid based game, having a 2D array of your map would be a good option

scarlet fractal
#

yeah something simple cries

#

I have a buildable Tilemap

plush coyote
#

If you actually want an object to take up one grid position, then yeah, have a 2D array of your map

#

When you spawn the object, you can round the position to the nearest grid position and set that position to "taken" or whatever

scarlet fractal
#

my only condition for now is

if (buildableTilemap.HasTile(mousePosition)```
plush coyote
#

then just don't instantiate something if the rounded position is taken

scarlet fractal
#

ok I'll try this thank you

remote moth
#

he should go not completly in the correct direction .-.

Rotate to the object:

Quaternion GetRotationToTarget(Transform target,Transform i)
    {
        Vector3 targ = target.transform.position;
        targ.z = 0f;
        
        Vector3 objectPos = i.position;
        targ.x = targ.x - objectPos.x;
        targ.y = targ.y - objectPos.y;

        float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
        return Quaternion.Euler(new Vector3(0, 0,   angle));
}

Move in this direction:

transform.Translate((transform.up / 2) * 1);
plush coyote
#

that's a lot of code to get the direction to the target

#
Quaternion GetRotationToTarget(Transform target,Transform i)
{
  Vector2 dirToTarget = (target.position - i.position).normalized;
  float angle = Mathf.Atan2(dirToTarget.y, dirToTarget.x) * Mathf.Rad2Deg;
  return Quaternion.Euler(new Vector3(0, 0, angle));
}
remote moth
#

he got still in the wrong direction

plush coyote
#

But, you just want it to go towards the target?

remote moth
#

But, you just want it to go towards the target?
@plush coyote yes

plush coyote
#
Vector2 dirToTarget = (target.position - transform.position).normalized;
transform.right = dirToTarget;
transform.Translate(transform.right * 5f * Time.deltaTime); // 5f is just some arbitrary movement speed number
#

that's the whole code

#

No need for quaternions or angles

remote moth
#

and can i do that he rotate in the direction?

plush coyote
#

this code also does rotation

remote moth
#

this code also does rotation
@plush coyote ok, thx

spring ledge
#

Wait, you can just assign a directional transform to rotate it?

#

Never knew

plush coyote
#

Use it all the time for my 2D projects

#

but yeah, it doesn't really make sense that it sets it

#

or at least, you wouldn't think it would

#

given the rest of unity's properties

remote moth
#

he don't move correctly by me, i want to set once the direction

plush coyote
#

No clue what you mean by that

remote moth
#

by creating the object

spring ledge
#

I mean, it can't change transform.right without changing rotation and such to match, I just expected it to be a read-only thing

plush coyote
#

thats what I meant ^ @spring ledge

#

given the rest of unity's properties, you would think its read only

spring ledge
#

Yeah

#

Nice trick to know

remote moth
spring ledge
#

Whats that

plush coyote
#

Two black squares

scarlet fractal
#

@plush coyote since I have a GameObject manager I just added my GameObject position to a List of positions whenever it's instantiated. Does the job for now I might create a class with different methods later

plush coyote
#

nice

remote moth
#

i mean that
he does not hit the object, but passes it

plush coyote
#

who is he

#

and what do you mean he passes it

scarlet fractal
#

through it maybe?

spring ledge
#

next to it probably, since through it would be collisions

remote moth
#

and what do you mean he passes it
go past

#

sry, my english is bad xD

spring ledge
#

What passes what ๐Ÿ˜›

remote moth
#

he move in the direction of the blue arrow, but he should in the direction of the red arrow go

plush coyote
#

what is your full code

#

and are these objects children of any other object

remote moth
#

and are these objects children of any other object
@plush coyote he has not childrens

#

create projectile

void SpawnProjectile(Collider2D[] enemys)
    {
        GameObject a = Instantiate(shootPrefab) as GameObject;
        a.transform.position = new Vector2(self.position.x, self.position.y);
        for(int i = 0;i < 100; i++)
        {
            Vector2 dirToTarget = (GetNearst(enemys).position - a.transform.position).normalized;
            a.transform.right = dirToTarget;
            
        }
    }
plush coyote
#

Why is this looping 100 times

remote moth
#

Why is this looping 100 times
@plush coyote idk xD

#

becaus the old rotation variant

plush coyote
#

that's not a good answer

#

ah

remote moth
#

becaus the old rotation variant
@remote moth but wenn i do execute it once for a object has he not rotate

plush coyote
#

well, what is the code on the projectile?

#

That doesn't make sense, the loop doesn't do anything

remote moth
#

well, what is the code on the projectile?

 void Update()
    {
        if((self.position.x < -15f)||(self.position.x > 15f)||(self.position.y > 8f)||(self.position.y < -8f))
        {
            Destroy(this.gameObject);
        }

        transform.Translate(transform.right * 5f * Time.deltaTime);
    }
plush coyote
#

well this should all work

#

but get rid of the loop

remote moth
spring ledge
#

Click that projectile in the editor, then press W

#

and take a screenshot of that

remote moth
spring ledge
#

No

plush coyote
#

why does it have gravity

remote moth
#

No
@spring ledge what then?

plush coyote
#

is that the projectile?

spring ledge
#

the actual object in the scene

remote moth
#

why does it have gravity
no, i have gravity set to 0

plush coyote
#

Ah ok

remote moth
#

is that the projectile?
yes

#

the actual object in the scene
yes

spring ledge
#

As in

#

A screenshot of that

#

Also ffs Discrod stop dropping my messages

remote moth
#

A screenshot of that
@spring ledge of the scene?

spring ledge
#

Of the projectile selected in the scene

plush coyote
#

Discord dropping everyone's messages

remote moth
spring ledge
#

after you press W

remote moth
#

after you press W
when i press w do it nothing

spring ledge
#

Hrm

#

click Gizmos on the top bar there

remote moth
spring ledge
#

hmm should work then

plush coyote
#

Getting nearest enemy method has to be wrong. Everything else seems fine

remote moth
#

hmm should work then
nope

#

Getting nearest enemy method has to be wrong. Everything else seems fine
why is this method wrong?

Transform GetNearst(Collider2D[] Enemys)
    {
        Transform Nearest = null;
        float distance = 1000f;
        foreach (Collider2D x in Enemys)
        {
            float x_distance;
            float y_distance;

            Transform obj = x.transform;

            if(obj.position.x > self.position.x)
            { x_distance = obj.position.x - transform.position.x;}
            else{ x_distance = self.position.x - obj.position.x;}

            if (obj.position.y > self.position.y)
            { y_distance = obj.position.y - transform.position.y; }
            else { y_distance = self.position.y - obj.position.y; }

            float NewDistance = y_distance + x_distance;

            if(NewDistance < distance)
            {
                distance = NewDistance;
                Nearest = obj;
            }

        }
        
        return Nearest.transform;
    }
spring ledge
#

Thats an odd way to get distance

remote moth
#

Thats an odd way to get distance
yes, this my way to get the distance xD

spring ledge
#

Trying to think if that even works

#

No, it does not

remote moth
#

Trying to think if that even works
yes this work

#

No, it does not
why not?

#

i have try it, this method work

plush coyote
#

Yeah, his old rotation method was like that too

#

tons of manual calculations that could have been done in 1 line

spring ledge
#

Say one object is at 0,0, the other at 9,1, so it's 9 tiles away from the first object. but you'd calculate that as 9-0, 1-0, then 9+1 = 10
Another object is at 5,6, so closer. But 5-0 = 5, 6-0 = 6 -> 5+6 = 11. So according to that it would be further away

plush coyote
#

literally

float distance = Vector2.Distance(obj.position, self.position);
#

if it feels like you are reinventing the wheel, you are probably doing something wrong (or there is a much easier way of doing it)

remote moth
#

tons of manual calculations that could have been done in 1 line
this is, because that i unity yet not long using

plush coyote
#

but you could always google "get distance in Unity"

#

And the docs will tell you

remote moth
#

but you could always google "get distance in Unity"
i have it so do, how i do it in python previously