#🖼️┃2d-tools

1 messages · Page 60 of 1

teal gazelle
#

but if i dont have that on, the child sprites spin and it looks really dumb

teal gazelle
#

Ugh, im stuck between a rock and a hard place.
I can't use Freeze Rotation on because it completely breaks the physics simulation, it becomes totally unlike physics at all
but I also can't not use it, because then I basically have to recode the entire item system from the ground up to account for the root gameobject potentially rotating and rotating all of its children

#

like, I COULD write a script that freezes the children's rotation, except right now I want and am using the children's rotation sometimes for certain things, so then I would have to go through and re-write everything and manually unlock and lock the rotation as needed

#

whole thing is gross. :C wish freeze rotation just worked right instead of not working right

solar thicket
undone gorge
#

hello

#

i need some help coding a weapon switch system

#

i want the player when he dosen't have a weapon to pick it up

#

but if a player has a weapon and want to pick up anather weapon

#

i want the current weapon to drop and to switch with the new weapon

#

here is my attemp

#
 public Transform GunPosition;

    public GameObject CurrentWeapon;
    public GameObject WeaponInRange;

    public bool HasAWapon = false;
    public bool isInRangeWithWeapon = false;

    private void Update()
    {     
        if(isInRangeWithWeapon == true)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                CurrentWeapon = WeaponInRange;
                CurrentWeapon.transform.parent = GunPosition;
                HasAWapon = true;

                if(HasAWapon == true)
                {
                    CurrentWeapon.transform.parent = null;
                    CurrentWeapon = null;

                    if(CurrentWeapon == null)
                    {
                        if(WeaponInRange != null)
                        {
                            WeaponInRange.transform.parent = GunPosition;
                            CurrentWeapon = WeaponInRange;
                        }
                    }
                }
            }
        }
    }

}
#

@inland osprey , sorry for pin, but i need some help, i am participing in a gamejam and if i will stay to long at this point trying to figure this out alone i will lose time

abstract olive
abstract olive
#

As for your code, you just need to condense your logic a bit. For example (not tested, but for a general idea):

#
private void Update()
{
  if (Input.GetKeyDown (KeyCode.E) && isInRangeWithWeapon)
  {
      // If the player has a weapon, remove it first
      if (HasAWeapon)      
          CurrentWeapon.transform.parent = null:
      
      // Assign the weapon in range to the player
      CurrentWeapon = WeaponInrange;
      CurrentWeapon.transform.parent = GunPosition;
  }
}
#

In otherwords, first check if the player has a weapon then remove it. Then add the nearby weapon as the new one second.

#

You had it reversed.

teal gazelle
solar thicket
teal gazelle
# solar thicket Do you have the physics materials set up to be bouncy and combine properly? Othe...

I'm fairly certain I have the phys material / rigid body / colliders set up properly. I made a new debug gameobject and addForce'd it at a 45 degree angle, when Freeze Rotation Z is set to on, when it hits the wall it bounces perpendicular to the wall, but if Freeze Z is off, it bounces at an angle relative to its impact angle.

I hadn't considered zeroing out at the moment of collider hit, that's a good idea.

undone gorge
#

and olso thx for response

strange cove
#

Im having this problem so when i made my character animated it gave me an error and my enemy doesnt go towards the player anymore so i belive it is something with the follow script in the enemy so does anyone know how to fix this? error:

turbid heart
covert whale
#

try to reset and see if that helps with the error

#

cus it could be that the error isn't related to the following problem

timber shore
#

The sprite looks the opposite direction from where it's looking

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

public class veikehjas : MonoBehaviour
{
    private BoxCollider2D boxCollider;
    
    private Vector3 moveDelta;
        
    private void Start()
    {
        boxCollider = GetComponent <BoxCollider2D>();
    }
    
    private void Update() {
  float x = Input.GetAxisRaw("Horizontal");
  float y = Input.GetAxisRaw("Vertical");

  Vector3 moveDelta = new Vector3(x, y, 0f);

  transform.localScale = new Vector3(Mathf.Sign(x), 1f, 1f);

  transform.Translate(moveDelta * Time.deltaTime);
}}```
undone gorge
#

hello i have a problem

#

here is a vid of the problem

#

do u guys have any solutions ?

turbid heart
undone gorge
#

when the player picks up a weapon the weapon stays up freesed in the position it was when was in the player's hand

#

i need the weapon to fall on the ground

#

but the weapons have a trigger colider

turbid heart
undone gorge
#

ok and how to make it fall on the ground ?

turbid heart
#

fall? you want it to fall down using gravity?

#

if you rely on physics, there's no guarantee it'll land right side up

#

you could lerp its current rotation to the target rotation to fake the falling

undone gorge
#

idk i just want the weapon to be on the ground

#

not really to fall

turbid heart
#

then what's wrong with just setting the rotation?

undone gorge
#

the problem is just the position

#

of the gun when being "dropted"

turbid heart
#

you could enable gravity for the gun, but constraint the rotation of the rigidbody

#

and hardcode the rotation so that the gun is the right way up

undone gorge
#

disable the trigger than enabeling it when ist's on the ground and disabeling the gravity ?

turbid heart
#

use rigidbody to allow the gun to behave with physics. Use gravity to allow the gun to fall, but dont allow physics to rotate the gun as it falls. Just hard set the rotation of the gun. That's the summary

#

hmm..

#

honestly, I dont know. will the guns always be at the same y?

#

or will there be platforms

undone gorge
#

platforms

turbid heart
#

you could fake the gun actually

undone gorge
turbid heart
#

this is kinda hacky, but the guns you pick up have physics. and when you pick up the gun, you destroy it or disable it. Then just enable a separate gun object in your player's hand

#

So the ones on the ground can have physics, but the ones in your player hand is a different object, but has no physics

#

then when you drop the gun, you just.. spawn the gun object(the one with physics)

turbid heart
#

I'm rather proud of it myself, haha. Try it out if you want. I dont know how well it will work. good luck

turbid heart
#

you probably have to disable collision between the gun and the player.. but that'll be tricky on how you'll make the guns detect platform, but allow the player to pass through..

#

that part, honestly, I'm not sure

undone gorge
turbid heart
#

I'd love to hear what you ended up using, if you don't mind. all the best

undone gorge
dusky wagon
#

Is there any tutorial on making an object follow a certain line or something like a rail system for moving platforms? I have been trying to find some tutorials, but couldnt find any

#

Essentially what Im trying to do is:

snow willow
#

could put any object on it

dusky wagon
#

Lets say I have these sprites. I want to make a tilemap that lets me draw these. Then have my object automatically follow the line to the right until it hits the right dot, stop and then switch the direction

dusky wagon
snow willow
#

https://learn.unity.com/tutorial/-2cinemachine-dolly-cart-and-track-2018
Here's a unity learn on it. You can ignore all the camera stuff in there and just look at the track building stuff and waypoints

Unity Learn

In cinematography, the term “tracking shot” refers to a scene where the camera moves alongside whatever it’s filming. To get the shot, the camera is mounted on a dolly that’s then placed on a track. As the scene is being filmed, the camera moves along the track. In this tutorial, you'll set up a Cinemachine camera to make a tracking shot.

dusky wagon
snow willow
#

would be pretty easy to do with the dolly cart I think though. Just build a track using the positions of those tiles

dusky wagon
snow willow
#

shouldn't be that difficult I'd think

#

actually - knowing the order in which the tiles were placed might be a big challenge

dusky wagon
#

Oh that doesnt really matter, I want to follow the track after certain rules

snow willow
#

it does matter though

#

if you want to build a path based on the tiles

dusky wagon
#

But if I build the same path in a different order, the path should be the same

#

But I have no idea where to start. Where would be the track script if all of the different tracks are on the same tilemap?

snow willow
#

using a particular tile type as the "walkable" tile

#

and generate a path that way

#

then you could use that path to either run your own custom code that does the patrolling or use those points to build a dolly track or something similar

dusky wagon
#

Hm okay maybe I want to do that

hot fog
#

hi so i want my boss character to bob up and down but when i make the animation when it finishes and loops back it waits for a split second and doesnt look good ho do i fix

snow willow
#

what does that mean

primal pivot
#

I have a weird issue, for quite a while, and only now noticing how to replicate it. So whenever i remove something on my tilemap (as in, on the grid so that square no longer exists in the scene) and i move to where that tile was, it will crash me, always. 🤔

#

So for example if i wanted to remove a wall in the scene on the grid, if i go to where it once was, it causes a crash, and it's really peculiar. I can change the tiles, but the layout has to remain identical because of that.

undone gorge
#

????????

snow willow
#

use the layer collision matrix to set up what collides with what

undone gorge
snow willow
undone gorge
#

but the trigger won't be effected ?

snow willow
undone gorge
snow willow
timber shore
snow willow
#

set up the matrix so it works the way you need

#

and put the colliders on the appropriate layers

snow willow
undone gorge
snow willow
#

you put them on GameObjects that are on the layer you want

undone gorge
snow willow
#

with a different layer

undone gorge
#

it dosen't work

undone gorge
snow willow
#

collision layers work

#

idk what you did

#

check the layer of each collider involved

#

and the way you set up the matrix

#

the weapon colliding with the weapon isn't your concern here

#

it's the collision between the player and the weapon and the ground and the weapon

still tendon
#

i want to use the w and s buttons to rotate my object counter-clockwise and clockwise and also change the direction that the objects move

#

how would i do that

undone gorge
dusky wagon
dusky wagon
#

Okay maybe I should rephrase that

dusky wagon
snow willow
#

the rails make up the "traversable" elements of your graph

#

for A* to operate on

dusky wagon
#

Well I dont really want the shortest one, and there isnt an target

snow willow
dusky wagon
#

Is DDDD a singular rail?

snow willow
#

each D is a "rail tile"

dusky wagon
#

Oh okay

#

Well it would depend on which direction each one of the rails point to

snow willow
#

I think what you need is 3 tile types: rail start, rail, rail end

#

then you basically do A* from the rail start tile to the rail end tile

#

to find the path

#

the rails have directions?

dusky wagon
#

Yes the would all have two directions

#

Maybe I was a bit unclear when asking

#

For example here the black things are the rails. I want an object to just follow around this path for eternity and it doesnt matter what ever tiles are placed in the red squares, as each of the rails points towards its two neighbours

still tendon
#

i want to use the w and s buttons to rotate my object counter-clockwise and clockwise and also change the direction that the objects move
how would i do that

snow willow
#

so maybe giving each of those tiles a "conveyorBelt" script or something that has a direction field on it

#

that your follower object can read and determine which way to go

dusky wagon
#

Oh good idea

#

How would that work on the corner rails though?

snow willow
dusky wagon
#

But it would also need to signalize that you have to go into the middle first, and not diagonal towards the end point

snow willow
#

then goes in the direction the tile says to the next tile's middle

dusky wagon
#

Ah okay

#

Or maybe I could make each on of the tiles have an array of waypoints the that follower object follows? I would like to have more flexibility with the tiles

snow willow
#

there's a lot of possibilities. I'd look into rule tiles too which could help make placing these tiles a lot faster

dusky wagon
#

Yeah that was what I wanted to do any way

snow willow
#

like you could just have one rule tile selected and drag the path out and the rule tile will select the correct corner tiles etc

dusky wagon
#

But probably not in the intended way

#

I wanted to use it entirely for placing game objects, since I want to have multiple different possible corner tiles, and rule tiles only react to instances of itself and not other rule tiles on the same tile map

#

Or maybe I could make a custom rule tile script to make an option to also count any other tile on a tile map as a neighbor, but I havent found out how to do that yet

snow willow
#

I haven't messed with rule tiles much yet either but you can do a lot with the scripts afaik

turbid heart
turbid heart
#

Cool, thanks! I was missing that bit because i don’t have much experience changing the collision matrix, so i suggested a rather roundabout solution for the person earlier

dusky wagon
dusky wagon
#

Hm I found a solution online, but I have honestly now idea how it works.

public class MyTile : RuleTile<MyTile.Neighbor> {
    public int siblingGroup;
    public class Neighbor : RuleTile.TilingRule.Neighbor {
        public const int Sibing = 3;
    }
    public override bool RuleMatch(int neighbor, TileBase tile) {
        MyTile myTile = tile as MyTile;
        switch (neighbor) {
            case Neighbor.Sibing: return myTile && myTile.siblingGroup == siblingGroup;
        }
        return base.RuleMatch(neighbor, tile);
    }
}

This adds another option for the rule tile called Sibing and counts any other rule tiles that is based on the same script as a neighbour, although I dont see that part where it checks for the neighbour

primal pivot
#

I have this weird issue, where whenever i erase a tile in my scene, if anything enters that area, the entire engine crashes. Even if i disable the entire tilemap so it's not in the scene, entering the areas that were erased (and only those areas) will cause a crash, despite everything no longer existing...

#

I can replace tiles on the grid, and add them too. But erasing any of them will cause that when entering it 😦 so i'm rather stuck to this same layout

#

If i add new ones also, removing them creates the same issue. Little areas to crash at

undone steeple
#

Hi, how can I prevent a sprite from sliding after a jump?

#

I'm using this material for ground, but the sprite still slides

lean estuary
#

You need to use physics to take advantage of physics system

undone steeple
#

Uhm... the problem is that the sprite keeps bouncing or something similar

lean estuary
#

Both objects must have physics material set and moving object has to use dynamic physics and moved using Rigidbody methods.

#

There's physics tutorial on Unity Learn

undone steeple
#

Oh ok I found the problem, it was the box collider

honest python
#

how do I display objects in the inspector?

languid lily
#

Wdym

strange cove
#

Does anyone know why my character tps when he rotates by me pressing left or right? script: ```csharp
public float moveSpeed = 5f;
public float jumpForce = 5f;

private Rigidbody2D rb2D;

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

void Update()
{
    if (Input.GetKey(KeyCode.D))
    {
        transform.rotation = Quaternion.Euler(0, -180, 0);
        transform.Translate(Vector2.right * (Time.deltaTime * moveSpeed), Space.World);
    }
    else if (Input.GetKey(KeyCode.A))
    {
        transform.rotation = Quaternion.Euler(0, 0, 0);
        transform.Translate(Vector2.left * (Time.deltaTime * moveSpeed), Space.World);
    }

    if (Input.GetButtonDown("Jump") && Mathf.Abs(rb2D.velocity.y) < 0.000001f)
    {
        rb2D.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
    }
}

} ```

hidden temple
#

huh

strange cove
hidden temple
#

you went from 1 problem to another

strange cove
snow willow
#

And it seems like you're mixing up transform.Translate and also Rigidbody motion, as I see AddForce later down

#

you can't mix and match those

#

use one or the other.

strange cove
bleak sparrow
#

Anyone know what Animator is not playing an AnimatorController means? I'm trying to call an animation from a script located in my bullet script but I get that instead and well the animation isn't activated either.

hollow crown
#

Your Animator is missing its AnimatorController

bleak sparrow
hollow crown
#

one of them doesn't. Else it wouldn't be saying that

snow willow
bleak sparrow
frigid minnow
#

Any ideas why my Raycast2D is still hitting something that is on a layer set to ignore raycasts?

#
RaycastHit2D lineOfSight = Physics2D.Raycast(gameObject.transform.position, (other.transform.position - owner.transform.position).normalized);
#

Do I need to do anything particularly special in order to exempt layers set to ignore raycasts?

#

What's more, is they're detecting trigger colliders

#

So I don't really understand why

snow willow
#

what object is it hitting?

#

you sure the collider itself is on that layer?

frigid minnow
#

Just found out I can disable the raycast hitting triggers

snow willow
#

yeah you can

frigid minnow
#

But yep, it's definitely hitting layers it shouldn't

#

One sec

snow willow
#

Are you sure the collider isn't just on a child object that's not on the ignore raycasts layer?

frigid minnow
#

Effect is toggled to ignore raycast

#

It hits basically every collider regardless

snow willow
#

that's not how this works

frigid minnow
#

Wait what

snow willow
#

this is the collision matrix

#

this means Effect will collide with objects in the Ignore Raycast layer

#

it has nothing to do with raycasts

frigid minnow
#

Oh psh

#

Where's the toggle for that then?

snow willow
#

your object has to actually be in the Ignore Raycast layer to be ignored by raycasts by default or you have to use a layer mask in your raycast to filter out layers you don't want.

frigid minnow
#

I see! That's very helpful, thank you :]

honest python
#

even tho I set my aspect ratio to be the only available one in Player settings, in the build the cam is not the same as in the editor

#

and is less wide

frigid minnow
#

Your build will save preferences if you've previously resized the window in an earlier build

#

If you made a build, resized the window, then made another build with a specific resolution, it will still use whatever you resized it to in the past

#

That's my experience anyways

dusky wagon
marble badger
#

Hi, if i want to talk about Design pattern which channel should i use
can anyone tell me

#

@hollow crown if someone wants to talk about design pattern which channel should he use

hollow crown
#

Use your digression as to what it is about

marble badger
#

are you personally familiar with state design pattern

#

!ranks

lean estuary
marble badger
#

sorry

#

just realised

desert cargo
dusky wagon
#

I am working on a paddle for a pinball game. My original idea was to give it a hinge joint 2d, some angle limits and activate the motor whenever a button is pressed. It kind of works, but when you hold the button, the paddle starts going over its limits for a second and then teleports back which looks really weird. I am assuming that this is happening because the motor has an extremely larger amount of speed. Any idea how I could fix it?

dusky wagon
#

I have made a thing that disables the motor as soon as the paddle reaches its limit, but I cant seem to find a way to make it stop there and only go down again if you are not pressing the button anymore

limpid drift
#

hey guys i was wondering if anyone could help me with a bullet script

#

right now its really working weird and trying to get it perfect

mighty compass
#

Hi

#

Need some help

#

My 2d options such as creating a 2d object dissapeared

#

Someone?

high rover
#

can you show

mighty compass
#

Sure

#

Wait

sharp lichen
#

import the package/ restart Unity

mighty compass
#

Theres no 2d object

mighty compass
#

Do I import the 2D sprite package

sharp lichen
#

have you ever had 2D in the project?

mighty compass
#

Yes

sharp lichen
#

Any console errors atm?

mighty compass
#

Wait

#

I think that I was organizing files and moved what I wasnt suppoused to

sharp lichen
#

then move 'em back

mighty compass
#

But I don't know what file it is

sharp lichen
#

window -> package manager -> look for 2d stuff

mighty compass
#

I did that too

sharp lichen
#

and dont move files that you don't know about ;p

mighty compass
#

Cant find anything

sharp lichen
#

Have you got the view displaying Unity pacakges, or packages that are in the project

#

there are different views.. look around and learn the PM window

mighty compass
sharp lichen
mighty compass
#

Ok

#

wait

#

Im so dumb

#

Found it

sharp lichen
#

you don't need to say wait.. I already am waiting

mighty compass
#

Thx

prisma crow
#

how do they make that effect that sometimes an obstacle is rendered above player if player was walking from behind the obstacle in a 2d pixel game?

austere iron
turbid heart
#

I'm thinking of buildings in pokemon I guess

austere iron
#

Oh, you can sort based on y position as well. There are options to choose for sorting . . .

austere iron
#

Even if using sorting layers, you can sort objects within each layer individually . . .

snow willow
#

negate the sign

timber shore
#

So cs transform.localScale = new Vector3(Mathf.Sign(x), 0f, 0f); ?

snow willow
#

negate the sign

#
transform.localScale = new Vector3(-Mathf.Sign(x), 1f, 1f);```
livid wigeon
#
void Shoot()
{
    GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    rb.AddForce(firePoint.up * bulletForce);
}

currently, the bullets keep going at the same speed forever, how can i modify this code to make them slowly decelerate?

snow willow
#

in the inspector

livid wigeon
#

that works, thanks!

dusky wagon
#

How do I get information about a tile of a tilemap at a certain position?

#

Or to be clearer, that game object placed by the tilemap at a certain position

snow willow
dusky wagon
#

No. I have a rule tile that places objects on a tilemap

snow willow
#

oh

#

I think you'd have to keep track of that then? Maybe with a Dictionary<Vector3Int, MyObjectType> ?

#

or maybe that wouldn't work in the editor because dictionaries aren't directly serializable?

#

But maybe just a list of the object along with its tile coordinate

dusky wagon
#

Hm the problem is that the object only gets instantiated once the game starts

snow willow
dusky wagon
#

Okay let me look up how a dictionary works, havent worked with that before. Is it similar to a dictionary in python?

#

Okay yeah, seems to be

dusky wagon
snow willow
#

with the tile coordinate you spawned it at as the key

dusky wagon
#

So I put a script on the object and it adds itself to the dictionary in the awake method?

#

Yeah that should work. Thanks a lot for the help again!

snow willow
#

the code that spawns the object could also put it in

dusky wagon
snow willow
snow willow
#

you do:
world position -> tile coordinate -> the GameObject from the dictionary

dusky wagon
#
  1. Shouldnt it be the same as the object
  2. Not really, I mostly only care about the game object
#

Or do you mean when browsing through the dictionary?

snow willow
#

I'm assuming you're trying to do something like: click on the grid, get the object in that grid space, no?

dusky wagon
#

Not really, I want to got information about the gameobject of the tilemap of the tilemap the position an object is on

snow willow
#

oh the tilemap GameObject itself? Not a particular tile?

dusky wagon
#

Sorry I meant the game object of a particular tile

#

Assuming that the tile has an object

snow willow
#

so how do you know which tile?

#

is it based on a coordinate? A user clicking somewhere?

dusky wagon
#

Base on the coordinate of a game object

snow willow
#

right so - you'll want to use WorldToCell to get the tile coordinate that is closest to that object

#

and then it will let you look up the object from the dictionary

dusky wagon
#

Ah okay I was gonna use a method to round dont the objects position, but that might work as well

snow willow
#

it gets rid of all the guesswork

sly shore
#

Hey im trying to use unity to create a simple mobile game and i created a c# script but it wont let me open it to visual studios does anyone know why or how to fix it

sly shore
#

ok thx

waxen harness
#

what would be the "correct" way to swap out sprites in a tilegrid (at runtime, with user input for a mechanic that changes the season)? (Using 2D extras library)
f.e.: changing water to ice in winter, changing the sprite and changing it back when the player switches to a different season

  1. Do you put the ones that need to be swappable on a different tilegrid?
  2. Do you change the render layer on the camera to only render the ones you wanna see?
  3. Use the gameobject brush for literally everything (im pretty sure that doesnt use the tilegrid anymore so it doesnt seem as performant as using the tilegrid mesh generation)

Im considering the first option since its the simplest, the second seems less optimal becuase technically the objects are still active and the 3rd sounds like a sizeable amount of work
but im looking for some input in case there is a better way that I am mising completely (I usually do 3D stuff, and am trying out 2D)

#

I'm aware I could test the different ideas, but I'm trying to think about it before I do things so I learn to not just jump to implementing out of nowhere.

keen skiff
#

okay so i'm trying to make it where when you go in the radius of textboxPos then it sends a message to the console saying you're in radius, and when you're out of radius of the textboxPos the console will say you're out of the radius. Unity doesn't say i have any errors with my code, but when i get close to the textboxPos object when i play my game it still says i'm out of radius. (my code is below)
https://hastebin.com/afivegavep.cpp

snow willow
keen skiff
#

okay so apparently the player didn't have the player layer

#

I really thought i did that

#

thanks for the help

digital dagger
#

I have a question. How do I get the direction an object is traveling in? Like In a vector 2, so I can hook up animations.

late viper
digital dagger
#

Thats kinda the problem. A* is moving the enemy for me. For the player object I have the option to create a movement vector base on the input of the player and use that information to see where the player is moving and then rig it up to the corresponding animation. For the enemy I dont have such a movement vector, so I need to draw that information from somewhere else

rich iron
#

How would I rotate a 2d direction vector by x degrees?

topaz root
#

Change the Z-rotation in the transform.

rich iron
#
    {
        float moveX = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        float moveY = Input.GetAxis("Vertical") * Time.deltaTime * speed;
        moveTransform.Translate(moveX, moveY, 0);
    }```
I have this code for my movement right now, but the sprite im moving around feels like he's on ice. Is there any way to get more snappy movements?
#

Oh nevermind, turns out GetAxisRaw is what I should be using

grave quarry
#

Hey guys i have stumbled upon a problem where i cant add the value of my movement speed because i have a dash variable in my script how do i fix this? here is my code
rb.velocity = new Vector2(horizontal * activeMoveSpeed, rb.velocity.y);
i need to change activeMoveSpeed to MoveSpeed to make my movespeed work but if i remove activemoveSpeed my dash dont work
if anyone know fixes for this ping me

#

im trying to implement sprint as well as dash

turbid heart
grave quarry
#

yes my bad i was new to this will not do ti again hehe

blazing mica
#
    {
        RaycastHit2D lineOfSight = Physics2D.BoxCast(eyeSightPosition.position, transform.localScale, 0, Vector2.right * transform.lossyScale, sightDistance, detectableLayers);
        Gizmos.color = Color.white;
        Gizmos.DrawRay(eyeSightPosition.position, Vector2.right * transform.lossyScale);


        if (lineOfSight)
        {
            Gizmos.color = Color.green;
            Gizmos.DrawWireCube(lineOfSight.collider.bounds.center + lineOfSight.transform.lossyScale, transform.lossyScale);
        }
    }```

i m trying to use ```BoxCast``` to check for the red characters. However, using this code only able to check the ray to the right side and not the left, my code does indeed make the scale to -ve when they are facing left. Is there any problem exist in the code?

Blue dot = eye
White Ray from Blue Dot = Ray direction
Green Box = where the ray hits
Red Bar above Red Box = Rage meter when they see another red box
desert cargo
#

probably

blazing mica
#

however, when i was using Raycast instead of BoxCast, it was working fine 😩

#

if not using Vector2.Right , how would I tell it which direction to cast to

desert cargo
#

oh wait... lossyScale is (-1, 1, 1) when facing left?

#

I get it now

desert cargo
#

okay, how do you know it's not working?

#

I think it's just immediately hitting the red player

#

actually, sorry... where is it being fired from?

blazing mica
blazing mica
desert cargo
#

Ah, i see. So both blue dots are firing

#

I get it

#

Is it possible that the right box is being filtered by detectableLayers?

blazing mica
#

however, this all works when I was using Raycast

desert cargo
#

Yeah... So it's just not hitting anything?

#

If I'm not mistaken if (lineOfSight) will always be true

blazing mica
desert cargo
#

You need to check if (lineOfSight.collider)

#

Or does it coerce into bool?

#

Ah, it does public static implicit operator bool(RaycastHit2D hit);

#

Sorry, I'm not being helpful at all.

#

Your code looks fine to me

blazing mica
#

dont be, I appreciate any help

#

i've been tortured by this for hours too, if I cant do it the worst thing i can do is just revert back to raycast

#
    {
        //RaycastHit2D lineOfSight = Physics2D.Raycast(eyeSightPosition.position, Vector2.right * transform.lossyScale, sightDistance, detectableLayers);
        RaycastHit2D lineOfSight = Physics2D.BoxCast(eyeSightPosition.position, transform.localScale, 0, Vector2.right * transform.lossyScale, sightDistance, detectableLayers);

        if(lineOfSight.collider != null && lineOfSight.collider.tag == "Monster")
        {
            Vector2 distanceBetweenMonsters = lineOfSight.transform.position - transform.position;
            if (rageMeter >= rageLimit)
            {
                rageMeter = rageLimit;
                return;
            }
            rageMeter += (Time.deltaTime * rateOfRage) * (Mathf.Exp(sightDistance / distanceBetweenMonsters.magnitude));
        }
        else
        {
            if(rageMeter > 0)
            {
                rageMeter -= (Time.deltaTime * rateOfRage);
                return;
            }
            rageMeter = 0;
        }
    }```
#

the previous code was in the OnDrawGizmos, this is the actual BoxCast casting from

#

basically the bottom part is just how the meter filled up, so the problem should be still on the ray

desert cargo
#

Why do you want to do a box cast?

#

That will mean that they're less able to see each other. Is that the goal?

blazing mica
desert cargo
#

Because it's more likely to hit the environment

#

Consider the difference between trying to throw a dart or a basketball through a small hole

#

If you want to check LOS the best way is to do LineCast from one to the other and see if there's anything obstructing it

lean sleet
#

Is there a way to paint tiles from the tile pallete as gameobjects? I'm trying to create hidden tiles that the player can break but can't find a good way.

compact knoll
lean sleet
solid trench
#

someone help?

snow willow
solid trench
#

so why?

late viper
snow willow
# solid trench

Did you drag anything into the slot for chose_level in the inspector?

late viper
#

oh, he's doing it in setup, which is never being called

snow willow
#

Or - it looks like you have a Setup() method. Are you ever calling that method?

solid trench
#

ymmm no

snow willow
#

well there's your answer

solid trench
#

so what I am must correct?

late viper
#

you need to call Setup() somewhere

solid trench
#

in Chose_level?

snow willow
#

oops wrong reply

#

@solid trench

late viper
#

thats probably the real answer ^

solid trench
#

thanks

#

It still does not work :(

late viper
solid trench
#

because it is to be selected in the menu and assigned to the varible and when I click play, the scene is to turn on (I work here on 2 separate scenes

#

so why this is not worked?

#

??????

snow willow
#

When are you calling FindObjectOfType

#

When is the scene being loaded

#

Think about those things

#

they are very important

solid trench
#

if i am comment SceneManager I have a this error

solid trench
#

something help me?

dense igloo
#

Did i do something wrong? when I click on my sprite the color doesnt change

late viper
dense igloo
late viper
#

put a debug log in there to check if its actually being called

dense igloo
#

ooh how do u do that?

snow willow
grand cove
#

Anyone know if it's possible to add a shader to a tile inside a tilemap at runtime?

#

I would even be okay with adding that shader to all tiles of the same type

#

Answer to above in any case anyone is curious, yes it is possible, but each tilemap only has one shader.

fossil quest
#

guys can i apply Clean Architecture in Unity ?

left canyon
#

hey there I'm using this tutorial to try to generate a procedural map tilemap. The tutorial is in 3D so I'm doing my best now to swap it to 2d but I'm struggling. Any help would be appreciated! The GenerateTiles function is what I'm struggling with:

tutorial
https://www.youtube.com/watch?v=v7yyZZjF1z4
my code
https://pastebin.com/2HHbu50x

Learn how to create procedurally generated caverns/dungeons for your games using cellular automata and marching squares.

Source code:
https://github.com/SebLague/Procedural-Cave-Generation

Follow me on twitter @SebastianLague
Support my videos on Patreon: http://bit.ly/sebPatreon

▶ Play video
dusky wagon
#

How can I make my object move towards a certain point with rigidbody velocity, while stopping as soon as it hits the point and not shooting over it, no matter what the frame rate is? I have made something that moves the object towards its target using the .normalized property, but I am not sure how I can make it not go over the target. I tried stopping it, as soon as it is in a certain range of the target, but when the frame rate is to low, it just misses the point where it is close enough to the object and flies over it

remote moth
#

if is set the x scale -3 he flip in the other side but if i do that in the script the camera will show nothing then, but if is set it in editor it work without problems

meager mural
remote moth
dusky wagon
snow willow
#

and either adjust the velocity to not overshoot, or MovePosition it to the correct position or what have you.

#

This is one benefit of a fixed-timestep physics system, you know precisely how much time the frames will be. It's not subject to the whims of the rendering framerate.

#

The amount an object will move in a single physics frame is simply rb.velocity * Time.fixedDeltaTime

dusky wagon
#

Ah okay so I can just detect of rb.velocity * Time.fixedDeltaTime is larger than the distance?

#

But what happens if the frame rate is below 50 and the fixed update rate is 50?

snow willow
dusky wagon
#

Ah okay, so there is no way that it can overshoot?

snow willow
#

nope unless there are other forces or scripts acting on the object that change the situation

dusky wagon
#

All right, thanks!

worthy stump
#

Does anyone know if a Unity uses Sprite Atlases when you're playing in editor, or is it just for packaged builds? If its only for builds, is there any way to force the editor to use the atlas?

tepid lintel
#
{
    public Transform target;

    public float smoothSpeed = 0.125f;
    public Vector3 offset;

    void FixedUpdate()
    {
        Vector3 desiredPosition = target.position + offset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltaTime);
        transform.position = smoothedPosition;

    }
}

Why does this script on the camera make my player's movement look very jittery?

#

looks perfectly smooth if i just set the camera to be the child of the player and disable the script

still tendon
#

how do i adjust box collider for platform

dusky wagon
still tendon
#

i actually fixed it thanku

dusky wagon
#

Oh all right

still tendon
#

why is my player not going forward

#

friction is .4

#

and there is no error in console

#

oh wait it was gravity issue

dusky wagon
#

The force you are adding is incredibly small

still tendon
#

yes i found that thank you and sorry apparently i stuck on a problem for long i fed up i ask and then i find bug instantly lmao

unborn sundial
#

this prevents jitter

tepid lintel
#

huh i thought i done that already

#

imma try that

#

ah yea that works really well

#

thanks @unborn sundial

lean sleet
#

Is there a way to paint tiles from the tile pallete as gameobjects? I'm trying to create hidden tiles that the player can break but can't find a good way.

dusky wagon
#

You can use rule tiles for that

lean sleet
dusky wagon
#

Do you already have rule tiles set up?

lean sleet
dusky wagon
#

But do you kniw how to do it, or do you need a tutorial for that?

lean sleet
echo quest
#

im using an isometric diamond to create a triangle, is there a way to stop intense pixelation over large scaling?

tepid lintel
#

or use vector art for simple stuff like this

echo quest
#

how do i make it higher res?

dusky wagon
lean sleet
tepid lintel
echo quest
#

i did right click > 2d object > isometric diamond

tepid lintel
#

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float jumpForce;
    private float moveInput;
    public int dashVelocity;
    private bool facingRight = true;
    public GameObject Camera;

    private Rigidbody2D rb;

    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;

    private int extraJumps;
    public int extraJumpsValue;
    private int Dashes;
    public int DashesValue;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);

        moveInput = Input.GetAxisRaw("Horizontal");
            rb.velocity = new Vector2(speed * moveInput, rb.velocity.y);

        if(facingRight == false && moveInput < 0 || facingRight == true && moveInput > 0)
        {
            Flip();
        } 
    }

    private void Update()
    {
        if(isGrounded == true)
        {
            extraJumps = extraJumpsValue;
            Dashes = DashesValue;
        }

        if((Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)) && extraJumps > 0)
        {
            rb.velocity = Vector2.up * jumpForce;
            extraJumps--;
        }

        if(Input.GetKeyDown(KeyCode.LeftShift) && Dashes > 0)
        {
            Dashes--;

            if (facingRight == true)
            {
                rb.AddForce(new Vector2(dashVelocity, 0));
            }
            else if (facingRight == false)
            {
                rb.AddForce(new Vector2(dashVelocity, 0));
            }
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Obstacle") { FindObjectOfType<GameManager>().GameOver(); }

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "WinTrigger") { FindObjectOfType<GameManager>().YouWin(); }
    }
}

How do i make the dash system work with the movement system? At the moment it does completely nothing because of the normal movement setting the velocity every single frame

#

also sorry for big script

echo quest
tepid lintel
#

i'd avoid the default unity sprites for anything more than prototyping

echo quest
#

ohk
i did draw my own art but i cant do collision detection with it

#

then i tried doing a 3d model in blender and importing it but then it had issues with lighting and stuff

tepid lintel
echo quest
#

box colliders and rigidbodys can collide right?

tepid lintel
#

if the object with the rigidbody also has a collider then yes

#

also don't use a box collider for triangles

#

and make sure you use collider2d

echo quest
#

ohk
well for triangles id have to use a mesh collider right?

#

and i cant make a mesh from a png image

tepid lintel
tepid lintel
#

i meant unedited

echo quest
#

how do i edit it into a shape?

tepid lintel
#

you could even use a circle collider if you wanted but you need to edit it

tepid lintel
echo quest
#

oh wait

#

i see the button

tepid lintel
#

yea

#

use that

tepid lintel
echo quest
#

yeah the edit collider only does the 4 sides

tepid lintel
#

wait give me a sec need to check something

dusky wagon
tepid lintel
#

yea

echo quest
#

ey that worked thanks

tepid lintel
#

np

dusky wagon
#

How do you want your dash script to work? Do you want the object to have a constant velocity or just a big velocity at the start that slowly decreases?

#

@tepid lintel

tepid lintel
#

which might not be a good idea

#

but in just a small game i'm making for fun it shouldn't really matter

dusky wagon
#

Is disabling the movement while dashing an option for you?

tepid lintel
#

hmm

#

if i edit my code a bit

#

a big bit

#

then yea probably

compact knoll
#

your options for getting an AddForce type dash to work are to either disable movement for the duration of the dash (so the velocity isn't overwritten) or switch to using AddForce for regular movement too

dusky wagon
tepid lintel
dusky wagon
dusky wagon
#

But you can if you want to of course

tepid lintel
tepid lintel
#

how tho?

compact knoll
#

it's pretty common for platformers

tepid lintel
dusky wagon
#

You can just put the line that sets the velocity of the rigidbody in an if statement and make a boolean to determine whether the player is dashing

dusky wagon
tepid lintel
tepid lintel
tepid lintel
#

and 1 more question

#

how difficult is it to make the player not have as much control in the air as on the ground?

dusky wagon
#

What exactly do you mean by that?

tepid lintel
#

like if you jump right you can't change your direction to left unless you double jump/dash until you touch the ground

#

not change direction but just change your velocity

#

yea you probably know what i mean

compact knoll
#

you would basically do the same thing you're doing with the dash. just prevent movement input while not grounded

tepid lintel
#

but

#

i still want some small adjustments to be possible

#

and double jumping

compact knoll
#

sounds like you definitely want to switch to using AddForce for regular movement. You can then reduce the amount of force you are adding per physics frame when not grounded, this will make it so that only small/slow changes are possible while in the air

tepid lintel
#

well

#

time to rewrite my entire movement script

#

gl me

compact knoll
#

it's really not that big of a change to be honest

tepid lintel
#

huh

#

well how do i fix the sliding and accelerating problem?

compact knoll
#

friction on walkable objects and higher linear drag/mass (these last two are settings on the rb2d)

tepid lintel
#

won't the friction make the player get stuck on the edges of platforms?

compact knoll
#

well the linear drag and mass are the two biggest factors, you don't necessarily need to use friction, but it does help.

tepid lintel
#

ah ok

compact knoll
#

keep in mind you would probably also want to cap the amount of force applied every frame if you don't set up your mass and drag well enough otherwise you'll have infinite acceleration

still tendon
#

how do i get current animation name

compact knoll
still tendon
#

and i dont wanna put name of each animation as it is too long job i just want a way to get name of current animation playing

compact knoll
#

so i just want to make sure i'm understanding this:

  1. you have an animation that is causing a lot of lag
  2. you want to change to a different animation when there is specific input
  3. you think you need the animation name to accomplish this

is this all correct?

still tendon
#

yes lag is like when i press a key it first completes the current animation

#

then moves on

#

hmm?

compact knoll
still tendon
#

wait my transitions are correct ig alll i want is just to stop current animation and skip to another at a specific event

compact knoll
#

yeah do the thing i just told you to do.

still tendon
#

oh well alr thx

compact knoll
#

i promise that's the actual issue here

still tendon
#

oh yes i got that

#

thank

#

u

#

can u explain that clickDown thing

#

this is my code how i implement that in it as i think its for mouse clicks

compact knoll
#

you don't need the clickdown thing. move on to the actual answer

still tendon
#

like but the function needs that parameter so what should i replace it with

compact knoll
#

what function? are you still looking in the question to figure out your issue or did you scroll down to the answers? the person in the question is effectively trying to do what you were attempting, but that's not what needs to be done. read the answers not the question for the steps you need to take

still tendon
#

oh lol

#

thankss its fixed now

civic rock
#

not sure if gui questions work for this channel, but how can i change the font of GUI.Label to a font stored in a variable?

hollow crown
#

Pass a different GUIStyle to the Label with the font you care about

#

Note that you generally shouldn't be using IMGUI for anything other than debug menus or editor GUI though.

civic rock
#

is there a font parameter for the style?

#

also what else would i use to render text like this

civic rock
#

thanks!

wind orchid
#

Hey, I'm new to unity/c# (started this week) and I'm having some trouble with my game and can't seem to figure out what it could be. Any ideas?

snow willow
#

they continue to be independent and follow the physics simulation

#

If you change the body type to kinematic it will follow along with its parent

#

As for the jumping x position value in the inspector: the position you see in the inspector is the local position of the object which is why it jumps from 7 when not parented to a smaller number between -1 and 1 when it becomes a child object.

#

local position meaning position relative to its parent

wind orchid
snow willow
#

kinematic rigidbodies are not simulated the way dynamic bodies are

#

😛

#

they don't respond to forces or collisions

#

or move with velocity

wind orchid
#

so.. are you saying there is no way for me to get it stuck to my platform/move with it?

snow willow
#

One option is to use friction, which is how real life objects stick to moving platforms

#

The main thing that will require is that your moving platform:

  • has a Rigidbody of its own (you can make this kinematic)
  • Moves in FixedUpdate with rb.MovePosition rather than by moving transform.position or using an Animator
#

you can/should also look into PhysicsMaterial2D to customize the friction of your platform's collider

snow willow
wind orchid
#

thanks though

snow willow
still tendon
snow willow
#

2D physics are "side-on" not top-down

#

you could use 3D physics if you want though

still tendon
#

Ah alright thanks, i'll look into other things then

#

My game has a lot of physics objects, so using 3d physics would be laggy

timber shore
#

I'm getting the error "error CS0116: A namespace cannot directly contain members such as fields or methods" 6 times, even tho there are no namespaces in my code:

Rigidbody2D body;

float horizontal;
float vertical;
float moveLimiter = 0.7f;

public float runSpeed = 20.0f;

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

void Update()
{
   // Gives a value between -1 and 1
   horizontal = Input.GetAxisRaw("Horizontal"); // -1 is left
   vertical = Input.GetAxisRaw("Vertical"); // -1 is down
}

void FixedUpdate()
{
   if (horizontal != 0 && vertical != 0) // Check for diagonal movement
   {
      // limit movement speed diagonally, so you move at 70% speed
      horizontal *= moveLimiter;
      vertical *= moveLimiter;
   } 

   body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}```
The places:
1,13
3,7
4,7
5,7
7,14
9,6
14,6
21,6
timber shore
compact knoll
#

you need to put all of that into a class

#

i recommend going through some C# tutorials/courses to better learn how to structure your scripts

#

also maybe consider using an actual IDE instead of a text editing software that happens to have syntax highlighting

turbid heart
# timber shore

if you created a script through Unity, you wouldnt have that sort of code. That looks like something you copy pasted. You need a class that inherits from MonoBehaviour

#

like boxfriend said, use an actual IDE like Visual Studio or Visual Studio Code. maybe also go through the beginner scripting tutorial pinned in #💻┃code-beginner

lean sleet
#

Is there a way to paint tiles from the tile pallet as gameobjects?

I'm trying to create hidden tiles that the player can break but can't find a good way. I am using the tile pallet to create my 2D levels, but I want to use the same tile pallet to create tiles that the character can destroy, but look the same as the other tiles in the level. I looked into rule tiles but couldn't work out how to do it. Any help would be appreciated!

compact knoll
#

Attach game object to rule tile when setting it up then when you place a rule tile and the scene is loaded it instantiates the game object that is attached to it

pliant valve
#

Hello everyone, I want to make a complex system of character 2d movement, with such features as wall crawling, double jumps, etc. and with the further possibility of adding complex elements. I have a choice: 1) I tried to do the movement through rigidbody.velocity changing. But I ran into the following problem: I don’t know how to perform the exact BoxAllCast because I don’t know the exact distance that the body will travel with the changed velocity per frame 2) and using rigidbody.MovePosition is bad because, as I understand it, it does not pass in one frame, but I want have full control over the player, and if you make the controller through rigidbody.velocity changing, then you get a lot of stuck in textures, shaking in textures etc.
Please help me decide, maybe someone can share the sources of a complex movement system so that I can see how they implement it, and generally suggest about the best method for changing the position of a rigidbody

tepid lintel
#
using System.Collections;
public class PlayerDash : MonoBehaviour
{
    private Rigidbody2D rb;
    private int Dashes;
    public int DashesValue;
    public int dashVelocity;
    private bool isDashing;
    private PlayerMovement Player;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        Player = GetComponent<PlayerMovement>();
        StartCoroutine(Dash());
    }

IEnumerator Dash()
    {
        if (Player.isGrounded == true) { Dashes = DashesValue; }

        Debug.Log("Test");

        if (Input.GetKeyDown(KeyCode.LeftShift) && Dashes > 0)
        {
            Debug.Log("Test 2");
            isDashing = true;
            if (Player.facingRight == true)
            {
                Debug.Log("Test 3");
                rb.AddForce(new Vector2(dashVelocity, 0), ForceMode2D.Impulse);
                yield return new WaitForSecondsRealtime(1);
                isDashing = false;
            }
            else if (Player.facingRight == false)
            {
                Debug.Log("Test 4");
                rb.AddForce(new Vector2(dashVelocity, 0), ForceMode2D.Impulse);
                yield return new WaitForSecondsRealtime(1);
                isDashing = false;
            }

            Dashes--;
        }
    }
}```
Why doesn't my dash script work at all? is it because of needing to use a coroutine to make the script pause or because of something else? Only the first debug.log statement shows up
snow willow
#

This seems like a coroutine you should start from Update when the user presses the shift button down. And the input checking shouldn't be in the coroutine

tepid lintel
#

thanks

oblique flare
#

Hi, working on making a top down game. Im having troubles figuring out how to create pressure plates using the tilemap system in unity. Should my buttons ect not be in the tilemap and instead be on its own gameobject instead of part of the tilemap? Im not sure how to approach this, thanks for any answers 🙂

white cedar
#

why my ActivateCollision isnt called if canBeDamage is true?

ancient path
#

and use an else

white cedar
ancient path
#

was the last debug called?

white cedar
ancient path
#

okay, thank you

honest python
#

how do you fit a Text component to a box?

#

or at least a horizontal limiter

wind orchid
#

is there a way to make an if statement that says something along the lines of "If gameObject.RigidBody2D is colliding with a gameObject.RigidBody2D.BoxCollider2d whose tag == ExampleTag"?
I know there is a OnCollisionEnter2D/OnCollisionStay2D but I'm looking for a way to put it as an if statement. Anyone know how to format it correctly/if there's a way to do that?

dusk escarp
real moss
#

@wind orchid OnCollisionEnter2d(collision other) { if(other.gameObject.CompareTag("tag")){} }
you can also make different layers, but that's basically it.
if object has rigidbody in parent, it'll check that collider's tag. if you want some child limb then you need (other.collider.gameObject.CompareTag(""))

wind orchid
#

I think I should have mentioned, but the reason I wanted to do this was to put it in the void Update() part of the script and I know that OnCollisionStay2D acts like FixedUpdate(), so I wanted a way to put it in my Update() function

wind orchid
real moss
#

just make a coroutine

wind orchid
#

I'm not sure what that is 😅 sorry I just started with unity this week

real moss
#

OnEnter { if (tag){ StartCoroutine(Whatever()); } }
IEnumerator Whatever()
{
yield return null
}

wind orchid
#

I guess i'll have to look into coroutine's

real moss
#

the problem is with ending it when something exits

#

you can cache it, or you can put inside something else

#

either way without knowing what you're trying to accomplish i can't help anymore

wind orchid
#

alright, thanks anyway

real moss
#

actually i can...

Coroutine x
x = startcoroutine()

so you can end it with stopCoroutine(x)

and since you're comparing tag anyway you could just make an interface on it, and getcomponent on that interface, telling to start and end coroutine if you expect all of the objects with that tag to need it

finite garden
#

Does anyone know the best way to check to see if a 2D object can see another 2D object?

#

I'm making a top down shooter, and I want the enemies to become visible even if only their shoulder is sticking out

late viper
finite garden
#

Raycasting is something I know about, but Vision Cones sounds promising. I'll give it a look, cheers

limpid drift
#

could someone help me out?

#

currently i have a issue with my spell the velocity updates every frame but i only want it to do it once it fires looks once

#

this is my script atm ```csharp
void Update()
{
fire();
}
public void fire()
{
if (this.transform.position.x > Player.transform.position.x)
{
isFacingLeft = true;
}
else isFacingLeft = false;

    if (isFacingLeft == true)
    {
        transform.position = new Vector2(-Velocity, 0);
    }
    else transform.position = new Vector2(Velocity, 0);
}
#

i have it so when the player triggers the enemy hitbox its instantiates the spell

#

and then i got this script above attached to the object so not the enemy controller

turbid heart
pallid stirrup
#

^

limpid drift
#

so when the spells fires

#

its keeps on following the player

turbid heart
#

okay? what do you want to happen, and what is happening instead? @limpid drift

limpid drift
#

okay so right now something diffrent is happing

#

when i start the game the "spell" goes to a locked position

#

and when it should instatiates it goes to the other side of the world

turbid heart
#

What is happening right now?

turbid heart
#

okay, so the spell is ending up in the wrong position

#

what is it supposed to do instead?

limpid drift
#

when the player enters the enemy trigger

#

it should Instantiate and then the script does the rest

#

where it goes to the direction of the player

#

but right now once i enter the trigger zone it keeps spawning new spells on the same position what happend in gif

#

i want to to spawn on the mage

turbid heart
#

okay, what is the code that sets the position of the spell? Show the code where you instantiate the spell

limpid drift
#
private void FireBullet()
    {
        Instantiate(Spell, transform.position, transform.rotation);
    }
turbid heart
#

okay.. what object is this code attached to

limpid drift
#
 private void OnTriggerEnter2D(Collider2D Player)
    {
        if (Player.gameObject.CompareTag("Player"))
            StartCoroutine(AutoFire());
turbid heart
#

also, use {} even for one liners. It reduces the chance of logic error

limpid drift
#
 private IEnumerator AutoFire()
    {
        while (true)
        {
            FireBullet();
            yield return new WaitForSeconds(FireRate);
        }
       
    }
#

this should be all that is linked to the fire bullet

turbid heart
limpid drift
#

the enemy

turbid heart
#

you're introducing alot of objects, but I have no idea what is what

#

what's the player? what's the mage? what's the enemy? which is which?

#

you said you want the spell to spawn on the mage

limpid drift
#

player on the left and the mage is the enemy

turbid heart
#

is the enemy the mage?

#

okay

#

is there any code that moves the spell?

limpid drift
#

yes

#
    
        if (this.transform.position.x > Player.transform.position.x)
        {
            isFacingLeft = true;
        }
        else isFacingLeft = false;

        if (isFacingLeft == true)
        {
            transform.position = new Vector2(-Velocity, 0);
        }
        else transform.position = new Vector2(Velocity, 0);
    
turbid heart
#

you're setting the position here, you're not moving it

#

see, you're using =

#

you should be using += instead

turbid heart
limpid drift
#

so where do i put the +=?

turbid heart
#

do you understand what I mean when you said you're "setting the position to the velocity"

#

not moving the object according to the velocity

limpid drift
#

ooooooh

#

lmao

turbid heart
#

yeah I hope you get it

limpid drift
#

but where do i put the += in this line of code then?

#
private void FireBullet()
    {
        Instantiate (Spell, transform.position, Quaternion.identity);
    }
turbid heart
#

that's just to instantiate it

#

the movement should be in the code that's attached to the spell, right?

limpid drift
#

so ur saying this should be correct then

#
 if (isFacingLeft == true)
        {
            transform.position += new Vector3(-Velocity, 0 ,0);
        }
turbid heart
#

i assume? you should test it

limpid drift
#

okay so that does it but now i got the problem with

#

it does this every frame and i only want it to do it once

turbid heart
#

well then that just depends on where you call it

limpid drift
#
 public float Velocity;
    public Transform Player;
    public int BulletDamage;
    public bool isFacingLeft = false;
    Rigidbody2D rb2d;

    // Start is called before the first frame update
    void Start()
    {
        //transform.LookAt(Player);
        rb2d = GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    void Update()
    {
        fire();
    }
    private void OnCollisionEnter(Collision collision)
    {
        
        var damageable = collision.collider.GetComponent<idamagable>();
        if (damageable != null)
            damageable.DealDamage(BulletDamage);
        //Destroy(this);
    }

    public void fire()
    {
        if (this.transform.position.x > Player.transform.position.x)
        {
            isFacingLeft = true;
        }
        else isFacingLeft = false;

        if (isFacingLeft == true)
        {
            transform.position += new Vector3(Velocity, 0, 0);
        }
        else transform.position += new Vector3(-Velocity, 0, 0);
    }
#

how can i fix that since if i dont have fire() in update it will never execute that part of the script

#

but if its in the update then it will always be on top of the enemy since every frame it transforms back to the starting point

turbid heart
#

dont crosspost. you might want to delete this question so people dont waste time answering it here

tepid lintel
#

ok sorry

honest python
turbid heart
turbid heart
limpid drift
#

so when the spell get activated

mossy fossil
#

hi!

#

starting to understand scripting n stuff and

#

i hope this is the right place

#
public Transform poziceHrace;
    public float speed = 20f;


    void Start(){
        
    }

    void Update(){

        float pohyb = Input.GetAxis("Horizontal");
        poziceHrace.position += new Vector3(pohyb, 0, 0) * Time.deltaTime * speed;

    }
#

i use this to move the player left and right

#

but it makes him keep the momentum

#

and i want him to stop right when you stop pressing the input

#

any idea?

snow willow
#

GetAxis applies some smoothing to the value over time

mossy fossil
#

and raw makes you stop right away?

snow willow
#

try it 🙂

mossy fossil
#

it worksss

#

ayyy

#

thxx

mossy fossil
#

if i needed to set statically y in transform to some number

#

how do i do that ? 😅

snow willow
#

wdym by "statically"

mossy fossil
#

press E to set it to 1

#

stop press Q to set it to 0

snow willow
#
float someNumber = 5f;
Vector3 position = transform.position;
position.y = someNumber;
transform.position = position;```
mossy fossil
#

argh

#

so simple 😄

#

thanks

remote moth
#

if i rotate all spriterenderers, but how can if fix that?

tepid lintel
#

Why do my dashes go below 0 with this script

using UnityEngine;
using System.Collections;
public class PlayerDash : MonoBehaviour
{
    private Rigidbody2D rb;
    private int Dashes;
    public int DashesValue;
    public int dashVelocity;
    public bool isDashing;
    private PlayerMovement Player;
    public float dashLengthTime;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        Player = GetComponent<PlayerMovement>();
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && Dashes > 0)
        {
            Debug.Log("you have:" + Dashes + "Dashes");
            StartCoroutine(Dash());
        }
        if (Player.isGrounded == true) { Dashes = DashesValue; }
    }
    IEnumerator Dash()
    {
        isDashing = true;
        if (Player.facingRight == true)
        {
            rb.AddForce(new Vector2(-dashVelocity, 0), ForceMode2D.Impulse);
            yield return new WaitUntil(() => Player.isGrounded == true);
            isDashing = false;
            Dashes--;
            Debug.Log("you have:" + Dashes + "Dashes");
        }
        else if (Player.facingRight == false)
        {
            rb.AddForce(new Vector2(dashVelocity, 0), ForceMode2D.Impulse);
            if (Dashes <= 0) { yield return new WaitForSecondsRealtime(dashLengthTime); }

            else { yield return new WaitUntil(() => Player.isGrounded == true); }

            isDashing = false;
            Dashes--;
            Debug.Log("you have: " + Dashes + " Dashes");
        }

    }
}

Unless i made a logical error this seems like it shouldn't happen. Dashesvalue is set to 2 in the editor

rain geode
#

Can someone DM me to help me correct an error (canvas showing on scene view but not on game) ?

snow willow
#

Each will reduce the dash count once the player is grounded

tepid lintel
#

well how can i prevent this from happening?

snow willow
#

Make sure you only have one dash coroutine running at a time

#

Either with a bool or with a reference to the started coroutine

#

You have the isDashing variable already

#

Use that

mossy fossil
#

Hi

#

for some reason

#

my trigger does not trigger -_O

#
public class CollisionDetection : MonoBehaviour{

    private void OnTriggerEnter(Collider other) {
        Debug.Log("An object entered.");
    }
    private void OnTriggerStay(Collider other) {
        Debug.Log("An object is still inside of the trigger");
    }
    private void OnTriggerExit(Collider other) {
        Debug.Log("An object left.");
    }

}
#

and this code is in the bigger trigger

#

when they collide or pass or anything

#

none of this prints

snow willow
#

You need the 2D ones

mossy fossil
#

oh my

snow willow
#

Other thing you need is for at least one of those objects to have a Rigidbody2D

mossy fossil
#

do i Just type 2D behind these xddd

#

even if it is an invisible trigger field?

snow willow
mossy fossil
#

kk ima look it up

snow willow
mossy fossil
#

is it better to move it around the player as the big field

#

or have it on the small square

#

that stays in the same spot?

#

(ill have multiple in one level)

snow willow
#

If something moves and has a collider, it should have a Rigidbody2D too

mossy fossil
#

wont it hurt performance ?

#

(I have no idea if rb stores stuff or not xd)

snow willow
#

No

#

It will help

#

Moving static colliders is not good

#

But regardless of performance having at least one Rigidbody is required for OnCollisionEnter etc

mossy fossil
#

oh

#

ummm

#
  private void OnTriggerEnter2D(Collider2D other) {
        Debug.Log("An object entered.");
    }
    private void OnTriggerStay2D(Collider2D other) {
        Debug.Log("An object is still inside of the trigger");
    }
    private void OnTriggerExit2D(Collider2D other) {
        Debug.Log("An object left.");
    }
#

these work

#

but

#

I have the collider like this now

#

and the white box has also trigger collider

#

but it still doesnt print

#

i did bad again i suppose 😄

snow willow
#

Change the Rigidbody Body type to kinematic

#

Or it will just fall away under gravity

mossy fossil
#

ok you are a genius

#

or maybe im just too rarded

#

or both

#

😄

#

thanks

#

but is it even worth it using the on enter?

#

i mean

#

the on stay plays anytime it moves around right?

snow willow
#

On stay plays once per physics update while it's inside

#

It's usually better to use OnEnter/OnExit but it depends on what you're trying to do.

mossy fossil
#

oh i see thx

left canyon
#

does anyone know how i would go about instantiating objects from specific tiles on a tilemap? the map is procedurally generated but I have a small percentage of tiles that I set up to spawn around the map that would be used as spawners for enemies. Can't quite figure out the API but would appreciate it if someone here has worked with this before :)

opal socket
left canyon
solemn latch
#

@left canyon use the prefab brush from the 2d extras to add your spawner objects?

left canyon
solemn latch
#

I haven't used it, I just remember it being a thing.

left canyon
#

I dont know if i can automate the 2d extras brush. but that is an interesting thought

mossy fossil
#

heyyy

#

how do i sort layers

#

like

#

put background in the background

#

foreground in the foreground and so on ?

#

i cant find any tutorial that works

abstract olive
#

You set a value to the sorting order on the sprite renderer.

prisma ocean
#

Say I wanted to make a space ship construction thing in my game where, during runtime, you added rooms to your ship which would be a collection of tiles. So it could be adding a 5x5 box of walls to a 10x10 box of walls. Should I create a seperate gameobject and tilemap for each room or add the walls for each room to a single wall tileset for the ship

orchid pewter
#

does changing the gravity also change all other assets gravity too? is there a way i can only change the gravity applied to my player?

#

sorry for it being like this its from a youtube tutorial

compact knoll
orchid pewter
#

changing the gravity works really well but it seems to work for everything

compact knoll
#

Yeah physics 2d gravity affects all rigidbodies, the gravity scale only affects the rigidbody you set it for

orchid pewter
#

oh thats perfect thanks

orchid pewter
#

got this strange thing where my guy jumps at the right height the first time the game launches but then every other jump afterwards is too small

#

i forgot how to post code

#
        {

            rb.gravityScale = 3.0f;
        }
#
        {
            rb.velocity = Vector2.up * 6f;
        }
prisma ocean
#

how would I get a tile on a specific tilemap from a specific world or screen position? for example the position of the mouse on the screen?

snow willow
#

You're increasing the gravity scale the first time your y velocity is negative

#

That won't happen until after the peak of the first time you jump

#

from that point on you are jumping with triple gravity

orchid pewter
#

@snow willowhe jumps the 6.0f height the first time i launch the game but every other time its more like 2.0/3.0 height

snow willow
#

Did you ignore what I just said?

orchid pewter
#

oh i got it now haha

#

i got a little confused

#

sorry about that 😄

#

forgot to revert it back to normal gravity

mossy fossil
#

is it possible to flip cinemachine ?

snow willow
mossy fossil
#

i know how to flip the player

snow willow
#

You mean just... move the camera?

mossy fossil
#

and everything insidhe him

#

yes

#

but the camera follow him

#

the way that he is mostly on left

snow willow
#

Cinemachine is an entire library devoted to moving cameras and pointing them at things

mossy fossil
#

i cant find how to do so 😄

snow willow
#

yes it is possible lol

mossy fossil
#

whenever google doesnt help i come here

snow willow
#

What is your setup exactly?

mossy fossil
#

wym

snow willow
#

I mean

#

you have a CinemachineVirtualCamera, yes?

#

how is it configured?

mossy fossil
#

yes

#

its just set up to follow the player

#

and i moved it like so

#

also there is one functional script and second prepared for this flip im talking about

#

the fucntional just freezes y movement

snow willow
mossy fossil
#

they dont open

#

when i "open them"

snow willow
#

the little arrow dropdown

mossy fossil
#

yea

#

it doesnt dropdown anythign

snow willow
#

should show something like this

mossy fossil
#

now ti does

#

xd

#

didnt do so minute before

snow willow
#

yeah so that follow offset

#

see how you have 5.17 for the x

#

what happens if you change that to -5.17

mossy fossil
#

it does the "flip"

#

it reverts

#

does the thing i need

#

how do i access that ?

#

with code

#

?

snow willow
#

SOmething like this @mossy fossil :

[SerializeField]
CinemachineVirtualCamera vCam;

void FlipCamera() {
  CinemachineTransposer transposer = vCam.GetCinemachineComponent<CinemachineTransposer>();
  Vector3 followOffset = transposer.m_FollowOffset;
  followOffset.x *= -1;
  transposer.followOffset = followOffset;
}```
#

cinemachine has its own component system sort of like how GameObjects have components.

#

the transposer is one such component

mossy fossil
#

Do i give this to the player or the cam?

#

(also thanks for this)

snow willow
#

You just would call FlipCamera() when necessary.

mossy fossil
#

oh i seee

#

so to the player it is 😄

snow willow
#

sure - just make sure you wire up the vCam reference in the inspector

mighty reef
#

Okay so I think this is the right channel for this. If not, I definitely apologize, just point me in the right direction. So I'm currently trying to figure out a solution to this issue. The player successfully loads above other game objects

#

However this happens when moving behind them

#

Sorting layers and order in layers are both set to the same, if that's relevant

#

I'm not sure if there's some sort of dynamic layer I can use that would easily fix this

mossy fossil
#

practically it works

#

BUT

#

i need to to move smoothly

#

to the new offest

#

isnt there some command for that ,

#

?

snow willow
# mossy fossil to the new offest

One simple option is to have two vCams set up. One with the + offset and one with the - offset. When the player turns around, switch to the other vCam

#

Cinemachine will blend the transition automatically

mossy fossil
#

@snow willow won't the performance go big owie ouch oofie?

snow willow
#

nope

#

Cinemachine is designed to have many, many virtual cameras in the scene at a time

#

that's why Cinemachine uses virtual cameras instead of multiple real cameras

#

the performance footprint of a virtual camera that is not currently the highest priority one is virtually nothing

mossy fossil
#

Oh

#

My

#

God

#

That's epic

#

Thx

nova remnant
#

a

#

uh i already solved this problem months ago but i lost the code and now i need help again lol
i'm on a topdown game where the camera normally follows the player
when LMB is pressed i want the camera to move to a point between the player's position and the mouse
it's just moving infinitely forward right now

#

Pls halp

uneven stream
#

hi, i just created a physics object with Dynamic mode and another with static

#

ok so whenever the dynamic object touches the static it pass trough

#

and i want it to collide with it

#

but idk how to do it so i need help

spiral swan
uneven stream
#

it does this, and go to the end of the universe, even if i put a static object

#

it should do this but it passes trough

snow willow
#

2D colliders

uneven stream
#

yup

snow willow
#

How are you moving the dynamic body?

uneven stream
#

the green box marks it

snow willow
uneven stream
snow willow
#

about the colliders?

snow willow