#๐ผ๏ธโ2d-tools
1 messages ยท Page 63 of 1
Somehow I can never seen to get ground checks to work. Maybe it's too much for my peanut brain. I always just do ground checks as if (rigidBodyPlayer.velocity.y == 0) grounded = true;
I'm gonna mess around a bit more with the code, if it doesn't work i'll just have to stick with my previous flipping at random intervals code that at least worked as primitive as it was
I seem to have figured it out, thanks for the help. Though I found another problem in doing so. Not sure why or how but my enemies get stuck on supposedly perfectly flat terrain.

hey guys, I have a question regarding two colliders with triggers overlapping
what happens, is when a player interacts with a gameobj that also overlaps with another trigger, both run at the same time. Is there a way to check if player is already activating a trigger?
for example this would happen when the colliders overlap
You could make a script to check which one's closer, and then only display the dialog for that one
i see, so check distance from player, and prioritize the closer one
okay i'll give that a shot, thank you
I know without the code there's not much one can say but both creatures are using (inheriting) the same script yet they are behaving differently. The size difference isn't the problem either as seen by the TestBots on the left. Any possible ideas to look into or not without seeing the code?
(Or does this go in #๐ปโunity-talk ? these channels are confusing)
If the code is the same, next thing to do is check how the objects are set up. I'd be particularly interested in those Ground Check and Wall Check references. Are they referencing the correct objects for each monster? I also notice the wall check is quite close to the ground for the slime. Could it be touching the ground by accident?
if you see closely in the pic (i've zoomed out to protect my sprites from copyright), there is a green thingy called the goblin in the middle right. There is a navigation yellow circle called the seeker, but whatever i do, they always keep the same distance, i couldn't make them together at an equal distance
any way to bring the yellow circle in touch with the green thingy
pls help
couple things unrelated to your issue:
- you should look into using a tilemap for your level instead of manually placing a bunch of copies of the same object everywhere
- nobody is going to come and steal your assets from screenshots because it's just not worth the hassle of doing so
as for your issue, could you please provide more information about what you want to happen?
i want that yellow seeker which comes from a unity package to meet with that yellow goblin, whenever i move the goblin, the yellow seeker moves with it
i assume you are using Aron Granberg's A* Pathfinding since there is an A* object in your scene. the basic AI Path script that comes with it will make it use the shortest path to get to its target which is set with the AI Destination Setter. If you want it to stop when it is within a certain distance of the target you can modify the options on AIPath to change the end reached distance and the "when close to destination" behavior.
If you want more in depth behavior than that, you will need to write your own script to handle it
yes, it has a yellow seeker right?
i want that seeker to meet with the green thing
but they move away from each other every time i try to drag it to each other
nvm i solved the problem
thank you
Hi! How can I parent an object with code to another object?
transform.parent is your current objects parent that you are running your code on
so you get a reference to a different objects transform that u want to parent to the first object and you go
transform.parent = reference
When importing a sprite sheet, I'm getting feathering/weird transparency even with Point (no filter) enabled. Any suggestions?
Tried that but no luck. Turns out my sheet was too long, causing it to be compressed that way. Thanks for the tip Iw as able to figure it out from that.
I have a question i was hoping you guys could help me with. i am trying to make a lazer beam enemy. i already have it so it aims at the player but now I want to make it so that if it doesn't hit the playe it doesent just stop at the players currnt position but it keeps going until it hits something.
use a raycast
idk how tho
im relitively new to coding
so im not that gud
im using a line renderer for the lazer beam with a texture sheet animation.
This tutorial goes over a lot. It does prefab projectiles, as well as raycasts with LineRenderer https://www.youtube.com/watch?v=wkKsl1Mfp5M
Let's learn how to shoot enemies!
โ Get the The Complete C# Masterclass for only $9,99: https://bit.ly/2xfXE6J
โ Instagram: https://instagram.com/brackeysteam/
โ Download the Project: https://github.com/Brackeys/2D-Shooting
โ Get the 2D Sprites: https://bit.ly/2p6VcvH
โฅ Support Brackeys on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยทยทยท...
ok thanks
i'll check it out and hopefully it helps
gotta sleep now tho
watch it tommorrow
I'm trying to add an animated tile to my tile palette with rules
I know how to create an animated tile and I know how to create a rule tile
but how do I combine both?
found it
rule tiles can be made animated very easily
Found an interesting thing this AM: Unity's Tilemaps have an undocumented bit in TileFlags. It's not in the enum definition in code but they appear to use bit 4 (i.e., 0x20 or 0001 0000) to signify whether or not animation is running. I noticed this in an inspector for an animated tile - there's an inspector button to turn animation on/off. I can post an image if anyone is interested. Curious to know if anyone else has ever seen this.
what does unity do when i change a tile in a tilemap through csharp tilemap.SetTile(coord, tile)
i have an array that sets the tiles of my tilemap but i do not know what excactly this line of code changes. does it create a new single tile with its own collider or will it be seemless with my previous compound collider?
the tile is an asset in your project folder. When you SetTile, it sets a reference in the Tilemap to that asset and calls StartUp, and GetTileData in the tile. The data returned from GetTileData is copied into the Tilemap internally.
thx. is there any popular unity game that has used a 2d array to set and change tiles in a tilemap in real time?
Don't know, but that's what I'm doing in my project which will undoubtedly be unpopular
does someone know how to move an object in the direction of the mouse? i searched on internet for 1 hour and i found only tutorial to move an object to the position of the mouse. thanks
I mean, this depends on a lot of things, which is probably why you had a hard time finding this.
You usually convert the mouse positions from the screen to the world position and make the object move according to it's current movement abilities to that position, depending if it uses path finding or something else.
use the difference of the mouse position and the transform.position
then normalize it
and then you got the direction on where the mouse is according to your gamobject
and to move it you can use different ways
fyi that ^ would look like (Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position)).normalized
I'd say the opposite
oh ok
you want to put the mouse position into a world position
then move the object towards that
i guess i didn't really understand the question then
i thought they wanted to move the object as it appears on the screen towards the mouse on the screen
can you explain, Camera.ScreenToWorldPoint(Input.mousePosition) does convert it to a world position
it converts the mouse position on the screen to where it would appear in world coordinates
and dont use Camera.main in update
ok well i wanted to demonstrate with one line
its no problem its just that camera.main finds the camera, so its better to use it to set a reference
That's not what ERSUCC put here #๐ผ๏ธโ2d-tools message
they put WorldToScreenPoint
on the object position
I'm working on a survival game where the user can place objects like chests and other structures. I'm looking to create some kind of effect that shows valid placement locations by highlighting them in green and invalid locations in red. The invalid locations are a mixture of non-pathable tiles on a tilegrid, and other gameobjects such as existing structures/trees/etc. It would also need to dynamically update as the player places or removes objects.
My current idea is to create another tilegrid of red and green tiles that I can just turn on and off as needed. I can loop through the impassible terrain tilegrid to find which tiles cannot be built on, but what would be the best way of accounting for the non-tile gameobjects? Or is there a better way to accomplish all this?
Im trying to make a movement script learning from a video it works fine and uses AddForce but it seems very unresponsive like my sprite gets dragged and when I try to press the other direction it waits like 2 seconds and holding it/spamming the key increases the speed
use different force types
ok
to increase the responsiveness you need to either increase the force amount, or decrease the mass of your object
ok
it pushes me hella far
like respsoniveness i mean like when i try to press d then a
it waits likee 3 seconds
wont increasing the force amount send me flying even more?
you have full control
add more force when slowing down to slow down faster
add less when already going fast to not fly off into the sunset
the code does what you tell it to do
Hey guys; I'm trying to make a top down sniper effect where the player right clicks to zoom out. I'm having a few issues; such as my camera moving way too fast due to the mouse being moved around during the aiming process; I tried to remedy this by slowing the rotation of the player but unfortunately I'm having issues making the turning slower.
I basically want to create a limited pan camera above a top down player; that can only go out as far as the specified zoom level; while maintaining a constant viewspeed.
@grand cove @ancient path thank you very much! Iโll see that later
Right now i'm using a raycast to detect conveyers under a item for my game (The point of the game is being a physics based factory game) to apply a force to the obejct, and it also checks which conveyer under it is on top. Is there any way to optimize this code?
void ApplyConveyerForceAtPosition(Vector2 position)
{
RaycastHit2D[] hits = Physics2D.RaycastAll(position, Vector2.zero, 0, LayerMask.GetMask("Conveyer"));
int mLayer = -1;
Conveyer c = null;
foreach(RaycastHit2D hit in hits)
{
Conveyer c2 = hit.collider.GetComponent<Conveyer>();
if (!(hit.collider is null) && c2)
{
int order = hit.collider.gameObject.GetComponent<SpriteRenderer>().sortingOrder;
if (order > mLayer)
{
mLayer = order;
c = c2;
}
}
}
if (c != null)
{
rb.AddForceAtPosition(c.transform.up * c.speed, position);
}
}
I just feel like there has to be a better solution them manually checking sorting order
I'm not even sure how that works, considering the raycast direction is zero..?
Guys, say I wanted to make an interactable map in a space exploration game like the one in starbound. Could you set me on the right track on how to handle this please? Should I make everything on a ui canvas, or should it be made out of gameobjects (the stars and planets etc)?
I saw something about using another camera to view objects on another plane and then render that in a window, would that be a good solution?
i am struggling with a super weird issue where my FOV shows up fine in the editor but the mesh isnt visible in game
has anyone experienced that before? i can share my code but i am not sure if its a code issue or if there is something i need to do in the editor
(orange dot is the issue)
Raycast 2d can detect colliders at the start of the ray
You mean if they're overlapping?
If the start position is within the collider?
Yes, if the origin of the ray is inside the collider it will return the collider. The solution I am using is working, it just seems like there'd be a better one
Why not use a collision event like OnCollisionStay/Enter/Exit?
Becuase this function is called for 4 points that might not necessarily have a collider there. 4 points on each item raycast down to see what is beneath them them apply the force at that position
Having 4 colliders, one for each point seems even worse then the raycasting
you say "raycast down" but your direction is zero. You just check a point.
Are these points on different parts of the item?
Yes,
Just using more effecient checks and sorting would help, since this function is called very often
Why do you need these 4 points? can't you apply force at the first contact point?
It lets conveyers rotate items if only part of it is touching it
Giving the illusion of more realistic physics then there are
a properly configured rigidbody would rotate as well.
Not in the cases I would want it to
Let me draw something
I'd expect the item between the 2 conveyors to spin here
hmm
The proper effect can be achieved in 3d physics with very simple code
But not 2d
Simple and physic based way of creating conveyors in Unity
Well, if it's performance that you're worried about, I think 4 circle colliders would do better than your raycasts. Assuming you detect collisions from the conveyor belt and not each item.
Each item does checks,
Hm that's a good point though
Having the conveyors check would mean a lot less calls
I'll give the circle colliders a try,
Thanks!
Wait but that leaves the problem of only wanting the topmost conveyer to affect it?
Make sure you cache stuff and don't use too much GetComponent in collision events.
Can they be stacked on each other?
They can be stacked on top of each other yes
They can be placed to cover only parts of each other
So disabling the entire conveyor would be problematic
hmm
Maybe lock an item to a conveyor belt when it's placed on it so that other conveyors ignore it?
Or better: place the item on a layer corresponding to the conveyer and let conveyors on other layers ignore it.
But other points still obey the conveyor they're over
Maybe just ditching the behavior overall would be easier
But I'm worried it will look odd
For now I'll just experiment
Thanks for the help
๐
I used a binary writer for all my saving
Hey how can i make difference between two objects for example like in game "Where's My Water?"
ok
Is it normal that Edge collider 2D object with rigidbody... goes through other objects (terrain), even goes through crazy big chunk of terrain, completely ingoring rigidbodies and colliders?
ah it's probably because im moving object with transform
hi im sure everyone knows the "getting stuck while walking" glitch to which the solution is using a capsule collider. But i have to use a box collider so are there other methods to fix it?
you mean character gets stuck on terrain sometimes? currently investigating stuck problems as well ๐
Im newbie so cant give an anwser. But i used Platform Effector 2D for terrain and it fixed similar problem for me.
try adding a physics material with no friction to the floor
also try disabling rotation on relevant axes on your rigidbody
i allready did that the problem is im using a tilemap collider
oh i see
do you know any methods to fix it?
not sure, i haven't used tilemap colliders before
have you put a composite collider on it?
the character is getting stuck between each tile's collider, a composite makes them all one collider
i didnt do that, thanks!
its still not working
how are you moving the object
i set the velocity
does it not move at all?
yes
do either the tilemap or moving object have a no friction material
no
oh wait
make a new physics material, set it to no friction and put it on one of the rigidbodies the colliders
the collider object got two colliders and one ridgedbody do all of them need the material?
only colliders can use materials
try putting it on both
i did but its still not working
i can still see the collision shape of the tilemap collider is that bad?
i use it for the jump and that works
yep
then you haven't added a composite collider 2d
i have
could you show a screenshot?
sorry i forgot to say you need to check 'used by composite' on the tilemap
Not sure where to ask this; This is a 2D viewport (the black background) on which there is a ui screen, on top of which there is the viewport for another 2D orthographic camera (the red background). The frame and the button are part of the UI canvas. I was wondering how I would make the button appear above the red viewport?
either you need another canvas over the 2D overlay camera or you could render the 2D overlay camera into a texture and use that on a RawImage Conponent in your UI
I have a problem with raycasting: I'm trying to make a ray that check for ground to see if you can jump, but it's randomly letting me jump infinitely above and below certain y levels. Does anyone know if this raycasting code is written wrong?
Ray contains something called distance
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
float distance = Mathf.Infinity
If you don't provide it, that's the default
I saw the documentation about the max distance, but how does that affect the 0.1 distance I'm checking for?
One your operation is prune to errors.
2 it also is unnecessary because you can set it in the method
You should debug what it's hitting regardless
Draw a ray there, see if it's not just hitting your character
Looking for a bit of insight on where to begin with making a 2d book in Unity whose pages can be flipped left and right
im seeing a few assets on the store like page curl pro
but I wanted to get some ideas from the community if theres a better route to go
anyone know any good roads to look down?
googling "making a 2d book unity" usually gives me scholarly books for learning unity
Wondering what happens when your values get negative. Do they? Like valueA lets say, 1 - valueB ( - 2 ) for example?
I would just use maxDistance and not hack my way around it to get the same result
on a canvas things render on the order of their hierarchy, so try putting the button after the red viewport in the canvas hierarchy
if they're on different canvases then change their sorting layer/ order in layer
is there any way to make my character to have ability to jump for 0.2seconds, even tho he went off the edge of terrain and already falling?
yeah this is called a cayote jump, a way to do it would be to have a bool for jumpEnabled, set it to true when the player first leaves the ground, keep track of the time either using a coroutine or a timer in Update, then set the bool to false if the player is still not grounded
then whenever the jump input is given you check jumpEnabled
Ah thx. That makes sence. Hope i can implement this in my mess of a newbie code... ๐
Can I ask why the PowerUP part is not functioning
basically the game is defend a planet while enemies tries to rush b it and you die if planet health reaches 0
which part specifically is not working?
The powerup part
The last part
Its supposed to double the ship's speed temporarily
you're not changing the speed anywhere
โ๏ธ you are changing timeCounter, but not the speed at all, just using it in your debug statements
So I need to change the last part?
yes, you need to actually change the player's speed otherwise the speed will remain the same
If you want to increase the player's speed then you'd change the variable called speed instead of the variable called timeCounter
So I'd assume writing speed = 4.0f; (which is double the default of 2) instead of timeCounter = 100.0f; would get you started
How about if I want a powerup where I do double the fire rate?
Daily round of asking if anybody knows how the tilemap renderer knows the Z (layer) value of a tile, and how (if) I can read it in a shader
the z layer isn't taken into account with rendering i don't think
Do sprites only work with the sprite mask or with mask and rect mask 2D aswell?
sprite mask for sprites and rect mask for ui, the two aren't interchangeable
ty
When someone is making a clickable map similar to something like FTL's map. Would you do that with game objects or with UI elements? What's the best practice?
UI elements would be my choice. If its just plain 2D, there is no reason to fiddle around with position in 3D space, just make it a 2D map with a mask or whatever you prefer. You can still use UI elements like simple gameobjects, scale them and what not.
you could do it as both sprites and UI, but i would do it with UI given all the extra unity components like layout groups, masks, text objects etc
and more options for scaling too
Can someone help? My trap shoots arrow. But i want arrow to get destroyer after it hits wall. So i used oncollision2d {Destroy(gameObject)}.
The problem is... my trap needs to have arrow object assigned so it will shoot it. After arrow gets deleted, it can't find object and it stops shooting. How to handle this?
have a prefab of the arrow and instantiate that, instead of instantiating from an existing arrow
ah... thx will try.
hi! what would be the best way of implementing a push/pull animation whenever my player object is on the right side of my pushable object and is moving right/left, and vice versa? tried setting up a raycast but that didnt seem to work
so how does the push/pull sequence start does the player need to input something then it grabs on?
yup! the player has a raycast, and if the player walks up to an object that has a certain tag on it and presses E, the player is able to drag the object in whatever direction they walk in
ah ok
so you have a reference to the object, and you know the direction the player is moving in
you can get which side the object is on using something like
(object.transform - player.transform).normalised.x and this will give you either 1 for if the object is on the right of the player or -1 if the object is on the left of the player
then you can check that against the player's velocity.normalised.x and if they match (so object is on the left and player is moving left which would both be -1 for example) then do a pushing animation, and if not then do a pulling animation
and i assume you already have some sort of system for flipping the sprite of the character depending on their direction, if not then that's just setting the transform's z rotation to 180 or 0 depending on if they're moving left or right
okay, ill try that! thanks! ๐
excuse the late response! i tried it and it didnt end up working, not sure what went wrong
Vector2 playerVel = rb.velocity.normalized;
if (playerDir == playerVel)
{
anim.SetBool("isPushing", true);
anim.SetBool("isPulling", false);
}
else
{
anim.SetBool("isPulling", true);
anim.SetBool("isPushing", false);
}```
this will only set it when they are exactly aligned
you should instead use the dot product of them i.e Vector2.Dot(a, b)
the closer the dot product is to 1 the more aligned the two vectors are
so you can do something like if it is more than or equal to 0.9f
a visualization if you're into those sorts of things https://twitter.com/FreyaHolmer/status/1200807790580768768
dot product - visualized โช
the dot of two normalized vectors, as shown here, can say how similar they are
a โข b = 1, same direction
a โข b = 0, perpendicular
a โข b = -1, opposite directions
you might also be able to see why it's sometimes called scalar projection~ https://t.co/vg8TwNZ8qs
704
2876
tried your suggestion, didnt end up working either
if (dot >= 0.9f)
{
anim.SetBool("isPushing", true);
anim.SetBool("isPulling", false);
}
else
{
anim.SetBool("isPushing", false);
anim.SetBool("isPulling", true);
}```
thanks for the visualization though!
np
try do dot with playerDir and playerVel maybe?
nope, didnt work
sadge
Hi everyone!
I have a 2D project with a specific situation in which I need to use a Z scale set to -1f for sprite renderers to allow my shader to work
In general, is there any worry with setting Z scale to -1 for a 2D project? Any particular impact that I should prepare for?
Thank you!
I was wondering how I would test to see if the box collider trigger on my object's child is overlapping.
I figured I could use something like this:
player.GetComponentInChildren<BoxCollider2D>().IsTouching() == true
But it didn't work, and I tried some other variations as well
GetComponentInChildren also returns the component on the parent if it has it. What doesn't work?
Because I am using it to check for the ground, it would need to check for the ground, but I'm not sure how to do it in the update loop/method
either keep track of whether it's currently touching with a bool that you set in OnTriggerEnter/OnTriggerExit or use the direct physics queries like Physics2D.OverlapBox()
Oh, thx for the info, I actually already got it working
I actually have another issue to resolve:
I have a jumping script I just made that is working really inconsistently, and it's referencing the same thing from earlier.
//Jumping Code
if ((Input.GetButton("Jump") == true) && (player.GetComponentInChildren<BoxCollider2D>().IsTouchingLayers() == true))
{
Vector2 movement = new Vector2(0, jumpForce);
player.GetComponent<Rigidbody2D>().AddForce(movement);
}
I got the child object to return true upon touching layers which works for now, but I would need to switch this out for something else later.
I am also getting this error where the jumps on my character are really inconsistent.
And yes, this is within the update loop
Why do you use that and not a Raycast shape?
Probably because itโs in update
And for physics FixedUpdate is better
And a tip is to save and not use get component in that update
there's a few things wrong here:
- cache your components rather than calling GetComponent every frame for better performance
- You should probably be using ForceMode.Impulse for a jump since ideally you would want all the force applied at once
- Because your jump is handled in Update, there are probably several frames where it is applying force before it is no longer grounded, you will probably want to use GetButtonDown so it only calls it on the frame it is first pressed instead of every frame the button is down.
Alternatively for that last part, you could handle your jump in FixedUpdate like No one suggested, it would be more consistent that way and you could continue using GetButton, you would just need a bool to check when to apply the jump force in FixedUpdate
Oddly enough, when I used GetButtonDown, it wasn't working, so I will probably be rewriting my code tomorrow with Impulses and a FixedUpdate method.
it wouldn't have worked very well without using the Impulse anyway
Also, I'm relatively new, so it may take me a bit to truly optimize it, so for now I'm going to get the child of the object.
But thank you for the suggestions
just cache the references in Start or Awake or something, then you don't have to call getcomponent, even if it is on a child
you already have a reference for "player" just get a reference to the rb2d and collider the same way you're getting the player reference
So for instance,
GameObject generalizedName = player.GetComponentInChildren<BoxCollider2D>();
So I can reference it more easily
You got the sprit
But instead of gameObject do BoxCollider2D
Because you are getting that component
sorta, that's not quite correct. You would want to make a class level variable for it and in start or awake you could assign the value and like No one said the type isn't correct.
ohhhhhh. ok
I'll make sure not to screw it up, lol.
so in order to be able to compare them you'll want to have two ints of just playerDir.x or playerVel.x
currently you're also comparing the y which isn't relevant and also since vectors are stored as floats using == can have issues since there can be floating point errors
so you'll need to convert the x of each vector to an int
TIlemap.Color won't work when access and changed at runtime by script, anyone know why?
Why is my polygon collider looking like this? Code at https://paste.mod.gg/flpimwfeitcu/0
A tool for sharing your source code with the world!
the circles are fine, but the poly collider seems like its being shrunk
how would i go about doing this? right now as is 'normalized' has a red line under it saying that float doesnt have a definition for normalized. i thought just changing what theyre checking specifically would work
Vector2 playerVelX = rb.velocity.x.normalized;
if (playerDirX == playerVelX)
{
anim.SetBool("isPushing", true);
anim.SetBool("isPulling", false);
}
else
{
anim.SetBool("isPulling", true);
anim.SetBool("isPushing", false);
}```
should i check for ground only when in air or all the time
other way round, so something like
int playerVelocityX = rb.velocity.normalized.x
you may have to cast it to (int) i forgot if you need to
how do you know if the player is in the air? by checking if it's grounded, so yes you would have to check it all the time
what if i check for if it is already grounded then do the ground check like:
if (!grounded)
{
do some raycast to find out if it is grounded
}
that way i can cut back on doing raycast all the time. It is a good option? Do people do that?
the if is in the update
but how can grounded be false in this case? if you only update the grounded variable while it's in the air, then if it comes to the ground and leaves again then the raycasts won't be called, and grounded will still be true
yeah i've used it a few times
should i check for ground in every concrete state
or
check for ground in the update of the context class
since one need to know all the time if it is grounded or not
if you have the state grounded and air, then check if it's grounded in both of their Update's, and change to the other state accordingly (so if grounded and it's air, then swap to grounded)
then you can have your following states inherit from either grounded or air, and so they won't have to run their own ground checks
i was referring to doing this, inside the context class as in the statemachine class:
update()
{
do groundcheck
currentState.update();
}
after building my state machine can i pick your brain about it some other time?
sure thing
i will ping you then
if you need a tutorial for a state machine for a platformer then this series is nice
https://www.youtube.com/watch?v=78PLsHnRXiE&t=325s
Discord Server:
https://discord.gg/uHQrf7K
Git Hub Repo for this project:
https://github.com/Bardent/Platformer-Tutorial
If you wish to support me more:
https://www.patreon.com/Bardent
We are moving on the using a FSM for the player controller now. To get started we need to take a look at the new input system! It's amazing!
Thanks. I am also currently checking that out
there's a red line under normalzied and it says that float doesnt contain a definition for normalized when I type "int playerVelocity.x = rb.velocity.x.normalized;"
i wrote out the line there and that shouldn't give you any errors
oh my bad, didnt swap the x. tried it and it says i cant convert 'float' to 'int'. when i try to put a parentheses around the int, it says that the left hand side of the assignment must be a property variable or indexer
apologies for all of the questions i'm new to unity ๐
oh so you need to cast it and that would be
int playerVelocityX = (int) rb.velocity.normalized.x
Do you really want it to be int? If you make it an int then it rounds the value down to the nearest full integer.
it's already normalized so it would be -1 or 1
yeah you probably don't want it to be an int
unless you specifically want either -1, 0 or 1
yes that is the intended set
because all that needs to be compared is if it's on the left or right
carry on then ๐
ok! that worked ๐ possibly last question, there's a red line under playerVelX where I'm comparing it to playerDirX saying "cannot convert int to vector2". how would i solve that? tried doing the same int casting thing on playerDirX but that just gave me a bunch of red lines.
int playerVelX = (int) rb.velocity.normalized.x;
if (playerDirX = playerVelX)
{
anim.SetBool("isPushing", true);
anim.SetBool("isPulling", false);
}
else
{
anim.SetBool("isPulling", true);
anim.SetBool("isPushing", false);
}```
for comparisons you would need to use ==, = is for assigning
you'll also want to do the same conversion to int but instead of rb.velocity it's the box.position - rb.position, and you forgot to change the type of PlayerDirX to int
i recommend doing some tutorials on the c# basics it'll help in the long run
will do! last thing, the 'position' in box.position is now underlined in red, says 'GameObject' does not contain a definition for position. why would that be? i have box as a public gameobject that i assigned in the inspector
int playerVelX = (int) rb.velocity.normalized.x;
if (playerDirX == playerVelX)
{
anim.SetBool("isPushing", true);
anim.SetBool("isPulling", false);
}
else
{
anim.SetBool("isPulling", true);
anim.SetBool("isPushing", false);
}```
because you need to access the transform, so box.transform.position
and the first line would need to be
int playerDirX = (int) (box.transform.position - rb.transform.position).normalized.x
reason for the brackets is because you want the normalized vector of both, not the first minus the normalised second
but generally if it's not in code blocks then don't take it literally
okay! thanks ๐ that got rid of the red line, but doesnt allow me to actually pull or push the item anymore ๐คฃ thank you though! i think i can figure it out
Anyone know how to fix this? My character gets taller and smaller after each animation
just change your animation so it doesn't change the overall size of the sprite
i.e. don't move the helmet part up so far or something like that
or move everything down a bit instead of spreading each part out vertically so that the feet stay in the same spot but the rest moves
i can't see an animation from a series of images like that sorry
but if you set the pivot point of the images to the bottom center instead of center center it should help maybe
try that before redesigning your animation
I tried that but nothing happened
hmm
make sure your images fill the area, it looks like there's whitespace around the images that could be affecting it
ah that's the problem
see how they're all different sizes
the green boxes are smaller in the middle
try making them all the same size
The green boxes only?
yeah
so the middle green boxes will have whitespace at the top
which is fine, it won't display
but that will ensure that when the image switches, the sprite stays in place
even though the image will appear to shrink the object won't
I tried making them the same size before but it didn't work but i'll try again
It worked ๐ thanks @grand coral
awesome! ๐
i don't think so
whats that?
the collider is defined separately, along with the sprite object in the hierarchy not with the image asset
that green box is for 9-slicing, a method of resizing sprites
so to change the size of the sprite image, use the blue circles not the green squares
if you move the green squares it only affects something when your resizing mode is set to sliced
Is there any way to make seperate colliders for an animation? because I have an animation when my character is very big and I want the collider to be big there aswell but then small when making another animation
yeah, you can change the size of the collider in a script
sure
this might be what you're looking for btw https://docs.unity3d.com/ScriptReference/BoxCollider2D-size.html
Thanks, I added you
how do i lock the movetowards function in only one axis?
Is there a way to call a coroutine only on the first collision
a boolean to keep track of if the collision is first collision, perhaps?
Well let me share my code
I have falling bombs that fall and land on platforms, after three seconds they blow the platform up, if it is touching it player it kills the players and the game is over
The bombs also destroy each other
The issue is if a bomb falls on a platform, then a bomb lands on it, the bombs blow up but the platform/player do not
no. see #854851968446365696 on how to post code please
it sounds like what you can do is just use a boolean that is set to true when the bomb touches something, then you can use that to ignore other collisions
also, instead of doing this
if (isTouchingPlayer == false)
{
}
if (isTouchingBlock == false)
{
}
if (isTouchingBomb == false)
{
}
you can do
if (!isTouchingPlayer || !isTouchingBlock || !isTouchingBomb )
{
}
but of course, it depends on the logic that's going to be in the if statement blocks
It doesn't do anything if they are false
Man, I love this, Still have not fixed my problem but it is way easier to look at
I am thinking I have to add the collisions to a list or array and then destroy all objects in said array
you could do something like
if (other.gameObject.CompareTag("Player") || other.gameObject.CompareTag("Block") )
{
isTouching = true;
//do your other stuff here
}
if(other.gameObject.CompareTag("Bomb") && !isTouching)
{
//do bomb touching stuff here
}
then you could call your coroutine only on the first one and if bombs kill each other just have it destroy itself in the second if statement instead of destroying the other bomb, that way you won't have to worry about the state the other bomb is in when that is called
Are you saying I should try that under the the OnCollisionEnter2D?
Yeah, that would simplify both methods since you wouldn't need a bunch of if statements in both. And you are already passing the collision into the coroutine so you can use Destroy(other.gameObject) instead of using the Find method since you already have a reference to it
Oh you're already doing that last bit for all but the player, but you can make that change for the player object too
Same Issue
Working the same as before though
For some reason the last collision is the only object I can destroy
You're also calling Destroy on this gameobject first which means the following lines aren't reachable, you need to call that last
In the coroutine right?
yeah, in the link you sent, just move line 73 down to below the audio manager line, you also don't need to use the isTouching bool in the coroutine
just call the coroutine from within the if statements in your on collisionenter and pass the object you want to destroy rather than the collision
basically you can change it to this
public void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player") || other.gameObject.CompareTag("Block"))
{
isTouching = true;
StartCoroutine(DestroyObject(other.gameObject));
}
if (other.gameObject.CompareTag("Bomb") && !isTouching)
{
StartCoroutine(DestroyObject(gameObject));
}
}
IEnumerator DestroyObject(GameObject other)
{
yield return new WaitForSeconds(delay);
FindObjectOfType<AudioManager>().Play("Bomb Explosion");
Destroy(other.gameObject);
Destroy(gameObject);
}
Cuts down on most of the if statements and should behave the way you want
I typically like to try and solve as many issues as I can on my own, Going to analyze that now that it is working and try and learn from it
Actually in that second if statement you can probably remove the tag check so it still dies from touching non tagged stuff
Only game components are the player, bombs and blocks.
I am real close to publishing this project, will be my first one, Everything is functional, Just going through and cleaning up bugs like this.
Well, my first project in google play
Well, I got excited too soon
Got to add the onexit back in
Player was being destroyed if they collided
even after they were not touching anymore
Is There a way to lock the movetowards function in only one axis?
set the desired position for the other axis to be the same as transform.position
thanks
I made a linerenderer which connects between 2 cubes but i want to make a new line and if it connects between these cubes
So how can i check if it connected between these 2 cubes?
something like this
if(line.SetPosition == pos1.position)
Can you not store which cubes it connects when you create the line?
Otherwise you can put colliders on either cube and do a Physics.OverlapBox with a small box at the end of each line, testing for which box they intersect with.
hmm ok ty
Does anyone know how to confine the edges of 2D Perspective camera? the cinamachine confiner works fine for Orthographic camera but not Perspective.
uhh idk if you can since perspective cams have different edges depending on distance
only way I can think of is a bit of math
perhaps there's some way to do that though
by math, do you mean like calculating if the frustum reaches a certain position, then stop moving?
uh
Let me make a quick drawing
perspective cam in 2d is like this
you can use trigonometric functions to calculate edge positions
but there's probably a simplier solution so search for that first
this sounds something that i would try to avoid ๐ฅฒ i think i will try to find alternative for my problem
i think i can complete the outer environment to compensate perspective camera
has anyone done anything with sprite shape where you set one of the vertecies to follow a moving game object?
Maybe you can also change camera's property that specifies the distance, then the white lines should be in proper position
Good Evening all, I've started adding in controller support for my 2D platformer and am having issues. Using the joystick horizontal to move my player causes him to sldie about the place, is there anything i can do to fix this?
Edit: I'm using the old input manager
do you mean they keep moving past where you expect them to? try GetAxisRaw or set your gravity really high in the input settings
by default, the input axes only gradually revert back to 0 when there is no input, based on how high the gravity is set
yeah they keep moving past were I expect them too. Setting the gravity higher has helped a lot, i'm gonna do some play testing
setting it to 300 helps a lot but after that there are no improvements and the player still slides about.
Why does the game think my mouse is at this tile when it's actually pointing at the one to the right?
There's some kind of offset? Could it be camera-related?
you'd have to share your code and how your tiles are placed etc.
If you don't want the gravity at all, use GetAxisRaw instead, which will always be the raw value without gravity. Beyond that I donno without seeing your code
i don't see any mouse-related code in there, how does the mouse know which tile it's over?
hmmm...are you sure the target graphic is correct? maybe that tile's button highlighting is pointing to the other tile (an off by 1 error in the instantiation, maybe?)
i don't feel like the built in system would be wrong about which object your cursor is over, but it's also tricky to really know
if i were you i'd shoot a ray out instead of having every object be a button
I swear it was working normally before, I don't know what I changed
Yeah I'll debug it again
So I made a gameobject with a sprite mask and changed the scale to fit my purposes, but now when I add objects as children to it, they have strange scales. Because they represent generated planets, I need to change their position based on calculated distances. How will this affect that?
Or should the sprite just not be scaled like that?
How would I go about calling a coroutine every time it finishes itself?
hi
im trying to make a flappy bird copy, basically
but unity aren't recognizing random.rangw
range*
http://pastie.org/p/0aIecWLRnwioTChHMGGvug
So the first link when a bomb blows up it does in fact destroy the blocks, players and other bombs
Which is what I wanted
Only thing is when a bomb blows up another bomb, the second bomb does not play the animation
The second script I sent you, Plays the animation when it blows up a bomb, but it also plays it when a block and player blow up which doesn't make sense
http://pastie.org/p/0aIecWLRnwioTChHMGGvug
Sorry
Anyone tell me how to fix this? I have tried referencs comparing tags, can quite get it righ
right
Read the error.
Yes, and what are you passing Random.Range, and what does it take?
i gonna try anything, wait a minute
why is it in quotes
it proboably thinks your trying to pass in a string
what errors is it giving now
check to ensure height is being set wherever it's supposed to be set.
This the appropriate channel for UIToolkit stuff?
are you sure the cinemachine confiner doesn't work for perspective cameras?
i added a box collider on 2 squares in my 2d game and box collider to my player but whenever player collides with an edge it changes its "form"
something like this
https://gyazo.com/645fc343e0ea29bdff3f2c05be6ba8b8
mark the colliders as trigger
then use OnTriggerEnter2D instead of OnCollisionEnter2D in your scripts
that might fix the issue
nah, if he uses colliders to stop another thing from passing through him that can fuck it up. this is pong so a ball wouldnt stop on a trigger
oh shit u right lmao
you can make it so the rigidbody is freeze rotation so the gameobject doesnt rotate
i forgot about the ball
with freeze rotation on, it doesnt collide at all just goes right thru it
nvm thanks
worked now
Can someone help me? If raycast hit player - player dies. Line renderers renders a line, but unlike raycast, it bugs out and teleports randomly, when i jump over it.
Hi everyone!
I'm making a 2d isometric game and I want to make the enemy chase the player (or target).
The chase part i got, but i can't make the enemy animation to sync with the movement (run walk-left animation when moving to the left, etc)
To walk towards the player, i use this to get the direction:
var direction = (_target.transform.position - transform.position).normalized;
But i needed to convert this to a Vector2.up, Vector2.down, Vector2.left or Vector2.right to be able to change the animation.
Any tips on how to do this? I don't seem to find anything on google, which leads me to believe that I'm doing something very basic in the wrong way.
Unity's vector page is good: https://docs.unity3d.com/Manual/VectorCookbook.html
Remember that 'Vector3.up' is literally just a vector3 with (0, 1, 0), down is (0, -1, 0) and that's true for each direction, so you might be able to just look at the axes and check their sign to get the data you need. Or a dot product would work.
alright so i'm trying to make a tile based on the tilemap when you click, but i've never coded with tilemaps before and have basically no idea what i'm doing. currently i'm having an error that's shown in the image. Does anyone have any way of doing this
(my code) https://hatebin.com/rbubwvbuua
Can someone help me figure out why I keep getting an UnassignedReferenceException and NullReferenceException?
This will take a minute to explain
No I know exactly what the error is
the problem I'm having is that I'm literally setting it equal to something and it's still giving that error
You cannot get an UnassignedReferenceException without trying to use a field Unity is serializing that is unassigned
#854851968446365696 has code posting guidelines
BossCollision.cs: https://hastepaste.com/view/PkV5P8EGCK
Thanks for the tip!
The article inspired me develop the following solution: https://gist.github.com/brenordv/dee23e5f992577adf3b39ef449444b12
I use Vector2.SignedAngle to calculate the angle based on Vector2.Up, then i figure out which way to look, depending on the result.
AdvanceDialogue.cs: https://hastepaste.com/view/NexWzjS7X
Going to have to see the errors
Parameters.cs: https://hastepaste.com/view/pJ4q
yeah I'm getting to that
these are the errors I'm getting
Show the inspector of AdvanceDialogue
So Boss has nothing assigned. You attempt to assign something using BossCollision though, but when does that happen in relation to it being evaluated, and are there multiple AdvanceDialogues in the scene?
There are multiple versions but they never are supposed to exist at the same time if all works correctly
Well it doesn't. That's the issue
It happens in the Start() method of BossCollision, so after it's instantiated
At some point you have a AdvanceDialogue that has not had its boss field assigned before Update runs, that's all this is
you can add logs to figure out what's going wrong on your own
how does AdvanceDialogue not have the boss field assigned at that point though
It should literally be assigned by BossCollision upon instantiation
I have no idea how your scene is set up
if there is an AdvanceDialogue without a boss collision this will happen
if there is a BossCollision on a disabled GameObject this will happen
There's nothing else that accesses it, and AdvanceDialogue is only ever created in accordance with BossCollision's start method
If there is an exception thrown earlier in BossCollision.Start this will happen
BossCollision is instantiated right before AdvanceDialogue, and is never disabled
the first error in my image is literally BossCollision throwing a NullReferenceException when I call gameObject
I cannot fathom how that would happen
yes
Only one thing on that line can throw an NRE
https://help.vertx.xyz/?page=programming/common-errors/runtime-exceptions/null-reference-exception
Access is denoted by the
.character (member access),[](array element or indexer access), or()(invocation.)
On the line throwing this exception, only variables that are being accessed via one of these methods are relevant, as only attempting to use a null variable will throw an NRE.
Oh I think I figured it out give me a minute
Ok I fixed it
thank you
I was calling GetComponent instead of GetComponentInChild in the Start() method
so yeah, it was a problem with how the prefab was set up
New issue
Instancing an object from a prefab and then trying to disable the instanced object later disables the prefab instead
Instantiate returns the instance, if it's not disabling the instance you're not using that
In BossCollision.cs from above, line 65 sets the variable to the instanced object, and then line 87 attempts to disable it
So the variable should be the instance
it isn't throwing any exceptions or anything either
These line numbers don't align to what's in the above script
uhhhhhhh
Let me check again, those line numbers are what VS gave me
Oh I changed the script
Lines 67 and 89
Well, it looks fine as far as I can see, though your logic is very confusing
Like... what's going on here:
emitters = new GameObject[emittersPrefabs.Length];
preDialogue.emitter0 = emitters[0];```
emitters[0] is just null
yes I realize, I was working on that while I sent the new code
and I'm a little unsure how in general you can get to instantiating anything into the emitters array if you're trying to access a value in it (that wouldn't be assigned yet) on line 66
I'm accessing emittersPrefabs for the prefab to instantiate a clone of, which is then assigned to emitters
Only on the line after that
Which means somehow you'd have to manage to get past accessing something that doesn't exist
ah
I revised it a minute ago so another script would access emitters[0], by the time that happens it does exist
the emitters are only supposed to exist after my dialogue closes, so my dialogue instantiates the first one right before destroying itself
I think I fixed it
Yeah, I figured it out, I think I've got these scripts completely finished now but I'll do more debugging later if I find problems
thank you again
I find it interesting that you can modify a prefab via a runtime script
that can lead to some weird problems if left unchecked by the game dev
From what I've experiencing so far, no, perspective camera cannot be properly confined by the space I've set in place.
I found this article about this issue but it's years ago, I couldnt manage to find a more updated info about this
https://forum.unity.com/threads/perspective-vcams-with-2d-confiners.508804/
Is there a way to limit speed on a rigidbody?
i don't know if there is a way built in but you could do something in fixed update like
if(rigidbody.velocity.magnitude > maxSpeed)
{
rigidbody.velocity = rigidbody.velocity.normalized * maxSpeed;
thank you
Fyi you can use ClampMagnitude
(same thing)
cool didn't know that
I have a rail like the one shown in the picture for my game. Whenever an object on the rail comes from the left then it follows the three points from A to B to C. If it comes from the right direction its the same thing in reverse, so from C to B to A.
Now I want to make it so that if an object drops on the rail it snaps to it and starts moving on it. So if it comes from the yellow point and has velocity towards the right it will move from B to C, if it comes from the orange marker with velocity towards the right it will just go to C and the same thing in reverse if it was to have velocity towards the left
There will also be different types of rails, some of them are more complex (e.g. a curve) and it would be good if I dont have to hardcode it for all of the different pieces, but I have no idea how I could detect the thing shown in this message
Can I have sprites have an invariable size on an orthographic camera no matter the orthographic size? or would I have to manually scale them
so if I had 2 objects at different distances, it would appear that they only got further away and not smaller
how do I create a meter that shows how high the rocket is in my game?
you can change the height of a ui image in a script, so all you have to do is get a reference to the rocket in that script and then scale its position to fit the meter
if you need details lmk
you might be able to calculate their proper scale in a script, but there isn't a simple button or option for that in the spriterenderer component afaik
I am building a game in unity that is a 2d Platformer using tilemaps for the platform and the background. I want to make it when the player goes up or the right or left that you always see the background without having to build the background so big. I know I saw in one tutorial on how to do it by making the background a child of the main camera, but the background was it's own object in the game and not a tilemap. Does anyone know how to do this with a background that is a tilemap?
I'm in the unity timeline
how do I disable movement while the timeline is playing for my player
Disable the player movement script
You can probably do that same thing
If you make it a child object of the main camera it will always move with the camera if thats what you want
How do I do that
make a reference to the script then do script.enabled = false
How do I do it with timeline tho
if you mean in an animator timeline then you make a function that does this, then make an event trigger in the animation and set it to that function
what is the standard way to change the skins of a 2d character and keeping the existing animations (e.g. run, walk will be same for all characters)?
hey im implementing a scoring system, Ive got my UI set up with a canvas and ive made an empty "ScoreKeeper" object in my hierarchy. Id like it to have a script attached which contains param: points per pickup, state: current score and on pickup it should increase the score and then the UI manager Update: should read the score from ScoreKeeper and update the scoreText does anyone know the best way i can go about this? its pretty basic just using a Player prefab and Coin prefabs
you can make a singleton for the score keeper, and have a function in it which is called on pickup, and in that function you can add to the score and update the UI
this would be instead of having the UI check every Update, which wouldn't be necessary if the UI was updated whenever the score changes
Hello Community, I wanna ask a question, how to make camera projection like Dani "Balls?" Games? When you controll the balls the camera moving as trajectory,sorry for so long question and bad gramma๐
No idea for 2d but for 3d there is
how do i make my aspect ratio, for an android game, the same for every device?
Does all devices have same ratio?
I cant put these sprites into the animator, are they the wrong file type or something?
Did you set them as sprites in the import settings?
i got it to work! ๐
hi so i wanna make a button that when i click it a menu apears
ok so just set the button on click to activate the menu GameObject
i dont know hot to make it activate that shi
jsut drag in the object you want to activate
and set the function to GameObject -> SetActive
and check the box so it passes in true
Here start with this https://www.youtube.com/watch?v=kQ2Qc_0MIyI
On the Button component, you can add the object you want to turn on in the OnClick events, and set it to active:"
That would be the "quickest and easiest" way to do it.
and how to make it invisible on start
Just turn it off in the hierarchy?
How Can I create this mask? I try to use Slider component, but it is filled by stretching my child component
for example
I tried it out by creating a secondary grid and tilemap, deleted the old background, and made the new one a child of the main camera. It worked perfectly. Thank you for the advice.
you can create a sprite mask and set a rectangular sprite as the mask, then change the height of the rectangular sprite to reveal more of the image
how do I get a 2D ui line in my 3D game?
you mean a text?
No just a 2D line in my 3D world
Cuz with line renderer it's rotated
Not directly facin the camera
canvas, either overlay or camera space, and make a square image with a small Y scale
why a small Y scale?
also using a square is a bit awkward for making a line go from point A to point B
i'm not sure but this isn't really a 2d thing so it may be better to ask in general code
oh alright
how do I create a meter that shows the hight of the rocket?
there are tutorials for how to make a health bar, you can do the same but on the y axis, then enter the current height of the rocket and the max height of the rocket
can you send the link
i'm not talking about a specific tutorial there's plenty out there
can you explain the last part
instead of using the player's health and the player's maximum health which most tutorials do, just use the rocket's height and the rocket's maximum height
how do I I get the rocket height and maxium height?
i don't know what your set up is like so i have no idea
if I send the project file will you help?
not your entire project file
send the relevant scripts and screenshots if necessary to explain
this is the script that makes the rocket go up
When launch button is pressed, the rocket is launched
can you have a look at #854851968446365696 for how to send code
and this doesn't look 2d to me it would probably belong in one of the other code channels
"lunch"
Ello, so uh I'm using a spritesheet (imported with multiple and sliced correctly) with these planet icons and applying them to sprite renderers, but the white-blue icons seem to have a tiny bit of the red star icons in them?
here's the import settings
Do you have to use the pixel perfect camera to make pixels look right or is there another way?
when you go into the sprite editor, you can choose custom and check that it's not overlapping, if it really isn't overlapping and that sprite really shows then it could be a bug so try re-importing / restarting unity
I can't get collisions to work
Forget my horrible graphics
when I start the ball falls because I have a ridgidbody2D on it
but it just falls straight through the ground which has a collider
does the ball have a collider?
And is the collider on the ground 2D?
yes and yes
- Does at least one of the two objects have a Rigidbody2D?
- Do both objects have 2D colliders?
- Is at least one of the colliders a trigger?
- Have you tired putting a Debug.Log in the function (outside the if statement) to make sure the code is being invoked?
- The playerObject has a Rigidbody 2D
- Both objects indeed have 2D colliders
- The Pickup collider is set to trigger
- I haven't tested Debug.Log, will do that now
also recommend:
if (collider.CompareTag("Ore"))``` instead of what you have
Hasn't made any difference :/
it's a minor performance benefit that's all
and less typing
anyway did you add the log statement?
It's triggering the debug yeah, but why isn't it destroying?
Obviously the ore is not tagged properly
is that the object that has the collider?
or is the collider on a child object of that
Yeah, that's the prefab
which GameObject is that
Same one
but wait
Doesn't have any children
the ORE has the PickupOre script?
Because that script seems to think that the object that it is colliding with is the ore
Ahh does it need to go on the playerObject?
yeah you have it backwards
you will get the player's collider in that function the way it is now
you always get the collider you collided with
not your own collider
(Nvm, I found another solution to my problem!)
its charming
no it's not
Yes it is
Bro if there is an entire ass single player MMO with that kind of art style I play the shit out of it
bruh
Just shitty pixel art The whole way that be hilarious
I hope they are placeholders lmao
yeah I'm just messing around rn I'm not good enough to try to make a full game
How can I spawn these in my game to be collectibles? I'm following inScope Studio RPG tutorial but i would like my items to appear in game and not spawn on key press
what are in the scriptable objects?
what are the differences between the different collectibles, you could just have one prefab that takes in an SO and sets its sprite / stats in its own script
i mean you can follow the tutorial and just spawn them before hand and not on keypress? like what is the method of spawning u want
there are three types - armour, weapon and potion. potions stack and armour and weapon are equipable.
random spawn around my char on pressing space key
so how is that different to him?
you can follow the tutorial and see how it's spawned and then give random positions when they're instantiated
oh so they're not supposed to be game objects just UI elements?
in his tutorial no. but i need them as such
u can make a generic base prefab that has a script that accepts a SO and sets all its values based on that
do you have an example maybe? would need a pick up option as well
if you want them to be picked up, have a prefab that takes in an SO, give it a collider2D and set it to trigger, then OnTriggerEnter check if it's a player and if so then spawn the SO in the player's inventory like it is in the tutorial
have a prefab that takes in an SO,
Sorry for dumb question, but how do i do that ? ๐
do all your SO's inherit from one base class?
yes
then have a public baseClass collectible where baseClass is the name of the class
then you can drag in that SO in the inspector
and have this script attached to a game object
and make that a prefab
ye
I add Trigger on that prefab right?
yeah a collider with IsTrigger
then have something like
void OnTriggerEnter2D(Collision2D other)
{
if(other.collider.gameObject.CompareTag("Player")
{
other.collider.gameObject.GetComponent<PlayerScript>().SpawnInInventory(collectibleType);
}
}
^or the other way around if u want
yeah, add a collider with Trigger, and make it a prefab
if you make it a prefab all you'll have to do is drag it into the scene and change the SO
and i assume you'll also want it to have some sprite, so you can give it a sprite renderer and change the sprite based on the SO
any way to automate changing the SO with the script when I spawn them?
because i need to spawn X different items with my random spawner
spawn the prefab with instantiate, and since collectible is public you can change that to whatever SO
So pick an item to spawn, change SO accordingly and spawn that prefab?
pick an item, spawn the prefab, and change the SO of the spawned prefab
so two highlighted lines go after Instantiate?
Instantiate returns the spawned prefab, so it would be like
GameObject spawned = Instantiate(//etc)
spawned.GetComponent<>//so on
Like this then?
How're you declaring ItemPrefab in the script?
If it's of type CollectableScript you would not need to call Get Component.
that works, but you wouldn't need to do GetComponent twice, just set what Icon is in the Start of the CollectableScript
since you've set what Collectable is and that's what it uses to get the Icon
As public GameObject ItemPrefab;
Why not public CollectableScript?
it's got more components on it like a collider and sprite renderer
You could always fetch those components.
Game Object reference should not be used unless you're only using it for it's Game Object functionality.
Best to declare as the type most used; less component calls - they're quite expensive if called a lot.
You'd have direct access to GameObject by simply using the gameObject property.
If needed ๐คทโโ๏ธ
wouldn't instantiating from a reference of CollectableScript spawn just a game object with that script
Nope
It's still the same object simply being referenced as it's component type.
Which would simply give you access to the component's members in addition to having access to the specific object; prefab.
oh ok
so yeah in this case it would be better to do public CollectableScript ItemPrefab;
CollectableScript spawned = Instantiate(//etc);
spawned.Collectable = //etc
to avoid a GetComponent call
Looks like a lot of calls are being made; more than once.
it would just be: ```cs
var spawned = //...
spawned.Collectable = ToSpawn;
spawned.Icon = ToSpawn.Icon;
Will try it in a bit, thanks ๐
It's working! ๐ฎ
Thank you guys so much!
๐
nice
welp new problem ๐
When I Try to add to inventory Inventory.Instance.AddItem(Collectable);
public void AddItem(Item item) {
if (item.StackSize > 0) {
if (PlaceInStack(item)) return;
}
PlaceOnEmptySlot(item);
}
what is null? is it Instance, Collectable or one of the variables in AddItem?
Seems like Instance is null
Because if I remove that line and print the name of the Collectable it works
if it's a singleton, you could be forgetting to set Instance = this; or you're doing it after you try to use AddItem
if you're setting the instance and trying to use it both in Start, then it can be out of order
If I set Inventory Active in the scene in works, huh
this is my singleton
private static Inventory _instance;
public static Inventory Instance {
get {
if (_instance == null) {
_instance = FindObjectOfType<Inventory>();
}
return _instance;
}
}
if this is on your Inventory script, then why do you need to do FindObjectOfType, you could use the this keyword?
this doesn't work with static , not sure how else to do it
if it's not static then Inventory.Instancecannot be done
non static script, with a static variable called Instance
then set instance = this
in Awake is generally where people do it
public static Inventory Instance {
get {
return _instance;
}
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
}
like this?
Hey Guys, So I am making a game where the player is a robot whose battery is broken and the player has to keep it charged and I was working on the Charging Mechanic and I used Physics2D.OverLapCircle() for it.
But for some reason, it always stays "true" even when the player/robot is not getting detected by the station (Charging Station)
public class ChargingStationScript : MonoBehaviour
{
[Header("References")]
[SerializeField] private Transform chargingStationTransform;
[Header("Script References")]
[SerializeField] private PlayerBatteryScript _playerBatteryScript;
[Header("Main Variables")]
[SerializeField] private float chargingSpeedRate;
[SerializeField] private float chargingRangeRadius;
[HideInInspector] public static bool isCharging;
private void Update()
{
//Checking if Player is in range of the Charging Station
isCharging = !Physics2D.OverlapCircle(
new Vector2(chargingStationTransform.position.x, chargingStationTransform.position.y),
chargingRangeRadius);
//Charging Player's Battery if in range of the Charging Station
if(isCharging)
_playerBatteryScript.batteryCapacity += chargingSpeedRate * Time.deltaTime;
Debug.Log(isCharging);
}
}```
This is the Script for the Charging Station... Can anyone help me out?
that seems good
now you'll need to have the game object this is attached to be active
and you should only access it in Start and not in Awake as instance may not be set then
currently you have no layermask, so if there's a collider attached to this game object it could definitely be detecting that
you can debug this by setting the result to a collider2d and logging the name of it
But, Is there a way to view, the OverLapCircle... Like the Outline of the Circle?
Cuz I want to fine-tune the Range of the "Charging Station"
there's Gizmos.Drawsphere or draw wire sphere
https://docs.unity3d.com/ScriptReference/Gizmos.DrawSphere.html
you can call this in OnDrawGizmos, make sure Gizmos is on and pass in the same variables as for the overlap circle
Ok Thanks Again!
np
no easy way really
best solution i've come up with is have several reference points inside one of the objects and check if they're all inside the other one
it won't be perfect though
collision.bounds is not going to be very accurate either
You should use this for checking if a point is in a collider https://docs.unity3d.com/ScriptReference/Collider2D.OverlapPoint.html
assuming collision is a Collider2D, yes
so after doing all this , my tilemap colliders stopped working? anyone has any idea why?
i don't think anything was done to do with the player or the tilemap, but check that there's a collider on both the tilemap and player, they're both not trigger and that one has a rigidbody (probably the player)
yep that was it. ๐คฆโโ๏ธ
you'll probably find that your items won't get trigger messages if they're not set to IsTrigger or if they don't have a script with OnTriggerEnter on them
They worked, I checked haha I was scared they wouldn't
great
Thanks again! ๐
why is my character in my game falling through the ground?
probably either the character or the ground or both don't have valid colliders
or rigidbodies
How do I fix that?
add a collider or a rigidbody component, respectively
Ok, i'll try it out.
Anyone know how I would generate an elliptical ring mesh over which I could tile a sprite? For example I want to make an asteroid belt that appears around a star like the line renderer used for the orbit of this planet, but as a tiled texture
You can draw a tiled texture with a line renderer
_>
If you look at this video the line I'm drawing with the blue circles is done with that technique
(ignore the rest of the video)
Isn't it because there are 64 vertices?
ok and your line renderer?
Run the game and then while it's drawn can you go to your material and start playing with the Tiling settings on your material?
aight
try setting it to very small numbers on x and/or y like .05
see if you can get it looking decent
and then also try setting it to high numbers
I don't remember which is correct
I seem to remember that when I did the line effect in the video above, I had to dynamically set the tiling for the material to get the shape looking correct based on the current length of the line
something like setting the tiling to 1 / lineLength
well
I went all the way from 0.01 to 1000
no difference
just a solid white colour
๐ค
lol that's interesting
unlit transparent with repeat per segment
OH
๐
just needed to change this in the sprite import settings lol
nice you got it
sorry yeah there's a lot of settings that need to be right ๐ค
Time to draw an actual sprite now and make an asteroid belt object ๐ฎ
And figure out how to make an elliptical collider lol
Hi guys, I'm trying to make spawn zones with PolygonColider2D. I use raycast, which detects the colider, but it detects the colider as if it was as big as camera.
Does anyone know why this is happening? (the script is attached to spawnZone game object)
btw I'm new to Unity, so I might not know some important basic stuff yet
idk if the code could help you, but anyway here it is
public class spawn_entity : MonoBehaviour
{
public GameObject enemyPrefab;
public PolygonCollider2D coll;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosVect3 = Input.mousePosition;
Vector2 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
// Cast a ray straight down.
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);
// If it hits a collider
if (hit.collider.isTrigger && hit.collider.gameObject.name == "spawnZone")
{
if (hit.collider.bounds.Contains(mousePosVect3)) Debug.Log("in bounds"); //this "if" result comes out as false
GameObject a = Instantiate(enemyPrefab) as GameObject;
a.transform.position = new Vector2(mousePos.x, mousePos.y);
}
}
}
}```
do you have any other colliders?
because your raycast could be hitting those as you don't have a layer mask
yes, I have tilemap colider, but it's not overlaping
according to Debug.Log function
so it could be because .bounds on a polygon collider aren't accurate
maybe try with a box collider and see if that helps
rb.MovePosition(rb.position + movementPosition * dashDistance);
Why does this dash not work?
rb = rigidbody2D
movementPosition are the axis inputs in a vector2
dashDistance is a simple float
is dashDistance 0?
Already found the issue, I put it in Update instead of FixedUpdate.
When doing a Raycast in 2D from mouse position you should be using Physics2D.GetRayIntersection()
Not Raycast
Thank you, will try that
a
Hello. I wanted to ask if you people could help me with some quick 'AI' for unity and I tried to write some code for it, despite having minimal knowledge about it. I'll send it after this message, but I would like to ask how I should make an actual 2d NPC AI that moves around and still tries to avoid objects and not just walk right into some wall for example. Here's the code:
[SerializeField]
float speed;
[SerializeField]
float range;
[SerializeField]
Vector2 maxDistance;
public Rigidbody2D rb;
public float p = 1;
private bool collided;
private bool A;
public Vector2 difference;
public Vector2 diff;
public Vector2 Adj;
public Vector2 length;
public Vector2 threshold = new Vector2(2f, 2f);
void Start()
{
SetNewDestination();
StartCoroutine(Thing());
}
private void FixedUpdate()
{
if (A)
{
rb.velocity = speed * Time.deltaTime * (maxDistance - Adj * 0b1100100);
}
else
{
rb.velocity = speed * Time.deltaTime * maxDistance;
}
}
public void OnCollisionEnter2D(UnityEngine.Collision2D collision)
{
collided = true;
StartCoroutine(Ahmed());
}
{
if (collision2.gameObject.CompareTag("avoidObj"))
{
A = true;
difference = collision2.gameObject.transform.position - rb.transform.position;
length = new Vector2(Mathf.Abs(difference.x), Mathf.Abs(difference.y));
AwaySee();
}
}
public void OnTriggerExit2D(Collider2D collision2)
{
if (collision2.gameObject.CompareTag("avoidObj"))
{
A = false;
}
}
void AwaySee()
{
if (length.x < threshold.x || length.y < threshold.y)
{
Adj = difference;
diff = threshold - length;
Adj = Adj * diff;
}
}
IEnumerator Thing()
{
for (int i = 0; i < 1000; i++)
{
p = Random.Range(1, 3);
if (p == 1)
{
speed = 0b0;
yield return new WaitForSeconds(Random.Range(0b1, 0b1100100));
SetNewDestination();
}
else if (p == 0b10)
{
speed = 0b10;
yield return new WaitForSeconds(Random.Range(0b1, 0b1011010));
SetNewDestination();
}
speed = 0x2;
yield return new WaitForSeconds(Random.Range(0.05f, 0b101));
}
}```
{
maxDistance = new Vector2(Random.Range(-0b1100100, 0b1100100), Random.Range(-0b1100100, 0b1100100));
}
public IEnumerator Ahmed()
{
if (collided)
{
speed *= -0b1;
}
yield return new WaitForFixedUpdate();
}
}
does any1 know a way of making a smooth sprite transition? sort of like how terraria does it with the biome backgrounds?
i haven't played terraria in a minute, but doesn't it just fade one background out while the other fades in? that would just require lerping the alpha channel of the SpriteRender.color
ohh... i forgot i could do that... thx
Hey im having some issues with some code, basically I want it to be so I click a character then he reacts and a score is added, heres the MESS of a script I got lol https://gdl.space/tasavacete.cs
its stored in the canvas
i think I screwed up hard and am kinda a nooba t it so ye
you are checking for input in Start. You need to do that in Update instead
actually that whole thing is super not good. you should consider going through the Intro to C# course pinned in #๐ปโcode-beginner so you can better understand how classes and variables and stuff work
real quit here
I'm having trouble adding a knockback effect to my game. I'm using AddForce() and trying to adjust the x position based on which side of the collider is hit. It generally works. I'd say 85-90% of the time it works exactly how I want but the other 10-15% of the time the knockback ends up being a knock-forward for some reason. I'm unsure exactly why but I'm very new to Unity so I'm hoping it's something easy I'm missing. Here's a gist of my class. https://gist.github.com/brandoncordell/ece347156beec387cf4f50bf139dbe58
I see you using AddForce, but also transform.Translate, the latter of those two will completely disregard physics, think of it as a mini teleport
Hey i have a problem with my (thats the problem idk where it is) that my 2d box collidor turns of and on every second. I think its a problem with my crouch
solution: DEBUGGING
D
do we have to talk abt it again?
google this: 2D box collidor turns of and on every second.
and see if u get a helpfull solution
answer: no!
Because of course you won't find it. It turning off and on isn't a general issue. There is no "make sure the turn off and on option isn't selected."
You said yourself you think it's a problem with your crouch, so start debugging that code. Use logs to track what's happening.
And start back tracking through your code. See where you tell the collider to turn off and on, and go back a step to what calls that and why.
But i followed a tutorial so thats not a porblem with any sort of wrong code or checkings
100% of the time, people who claim to have followed a tutorial actually didn't. Assuming you're only following the tutorial and not adding anything custom on top.
But anyway, there's nothing anyone here can do based off your question without more information. You need to be more specific about your implementation and such.
you just had an issue where you claimed that you followed the tutorial when in fact you didn't. You should know by now mistakes happen
So I was making my first 2d game but every time my character falls through the floor but I have all of the colliders on my character, I don't know what to do?
do you have a collider on the floor and does the player have a rigidbody
the player has a ridged body but I think the floor does not
only the player would need a rb2d. both do need 2d colliders though
does the floor have a collider
no
it'll need a collider
so do i give "tilemap" or "Grid" a 2d collider
you'll likely want a Tilemap Collider on the tilemap object
give the same object that has a tilemap component a tilemap collider and a composite collider, and check 'used by composite' on the tilemap collider
thank you it works
yesterday in animation i said that the animation didn't play on entering a scene which i managed to fix yet now the player does not work
{
if(timeBtwAttack <= 0)
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
Attack();
timeBtwAttack = startTimeBtwAttack;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Attack();
timeBtwAttack = startTimeBtwAttack;
}
else
{
timeBtwAttack -= Time.deltaTime;
}
}
is there a better way on doing this so i dont need to repeat everything?
KeyCode[] keys = new KeyCode[]{ KeyCode.LeftArrow, KeyCode.RightArrow };
bool keyDown = false;
foreach (KeyCode k in keys) keyDown |= Input.GetKeyDown(key);
if (keyDown) {
Attack();
timeBtwAttack = startTimeBtwAttack;
}```
Add however many keys you want to that array.
Wrote that on my phone so bear with me ๐คฃ
Best to put that array declaration outside the method too.
how would I exactly right this? when I type the word 'foreach' it says that its an invalid token
sorry I dont know much in coding
Hello i am trying to make a top down movement script but i am getting errors?
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * movespeed * Time.fixedDeltaTime):
}
}
so what're the errors
Assets\scripting\PlayerMovement.cs(18,82): error CS1002: ; expected
and
Assets\scripting\PlayerMovement.cs(18,82): error CS1513: } expected
what is ide i am new to all of this