#πΌοΈβ2d-tools
1 messages Β· Page 26 of 1
and also sometimes not look in correct direction
My code:- https://hatebin.com/udrnfafqdz
how can i get the speed of my rigidbody?
rb.velocity.magnitude is always returning zero
i'm moving my player using MovePosition in FixedUpdate
it returns zero, even when the player is moving
@wooden acorn so you will not using Rigidbody.velocity
might using transform.position +=
You have to use rigidbody.velocity
Yo, I'm making a previewer on a custom anchor tilemap. How should I do my positioning math so as the white sprite gets placed behind the target tile?
previewer.transform.localPosition = targetPreview.CellToLocal(cellPos) + targetPreview.tileAnchor; ```
I'm using a custom orientation as shown here
NVM, figured it out
Hi! New on c# If some one can help please tag me. Thank you. So how can I make a tile map that works like in the animation below? Its like if the player passes between the walls they show up but if he hits the walls he respawns but remembers where the walls are.
simple question, but how do i check the rigidbody's velocity when falling?
-y won't work sadly
or actually i don't think i need this atm, i'll come back to this if i got any more problems
void Update()
{
radius = planet.GetComponent<CircleCollider2D>().radius;
distance = Vector2.Distance(rocket.transform.position, planet.transform.position);
hightReadout.text = System.Math.Round(distance / 1000, 2) + "km";
}
this will only return 0.64 as a radius which is very wrong
its applied to a large object that's has a scale of 1500 on x and y but the script needs to be variable for objects of other size too
yeah nvm on my question, i got everything under control
well i figured out what my issue was but i dont know how to fix it so the script works with every size object. basically scalling factor changes the size of the collider but not the value that represents said size so it takes the radius * scalefactor to get the in game size
i figured it out i just got the scale from (gameobject).transfrom.localScale.x since its a circle x and y are the same
how do i make character align to ground on slopes/loops etc?
Anyone knows how can I control this rotation with the mouse, I don't understand Mathf.
private float Radius = 0.1f;
private Vector2 centre;
private float angle;
void Start() {
centre = transform.position;
}
void Update()
{
angle += RotateSpeed * Time.deltaTime;
var offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * Radius;
transform.position = centre + offset;
}
are you controlling with scroll wheel or mouse movement
Hi anyone managed to make 2d animation package work in version 2019.4.16 lts?
i would assume linking your mouse to rotatespeed?
maybe by storing two mouse locations, one before a fixeddeltatime, and one which is the present
then subtracting them
then using the magnitude as the speed your mouse moved?
something like this
Vector2 lastPos;
float MouseSpeed
{
get
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = -10;
Vector2 pos = Camera.ScreenToWorldPoint(mousePos);
float val = (lastPos - pos).magnitude;
lastPos = pos;
return val;
}
}```
Hello. I am a total beginner in game dev, so I was using a tutorial to make top down 8 direction movement, but for some reason MonoBehaviour doesn't work in my script or smth. I assume it's because of MonoBehaviour. It doesn't read some commands (like moveSpeed or rigidbody) or I assume it doesn't read them because their colours don't change. Anyone can help me? I have no idea if it's actually because of monobehaviour or maybe something else, however my script looks like this:
when the guy on the tutorial has it like this:
also, when I put in commands I don't have any of these:
i assume it's because I don't have this next to PlayerMovement.cs
oh yeah, and also, Unity displays this error:
which I don't know how to fix
and what it even means
what is global namespace? π€
what is anything in life really
@wispy fjord well to start, that error means you defined the PlayerMovement class more than once, so get rid of any extras
Hello! I'm working with interfaces at the moment and I have mouseover scripts on certain interactable objects. How would I stop the mouseover from happening when my mouse is on the interface and the object is behind it?
oh, okay, so I took care of that π thank you. Now there's another error π
The Rigidbody 2D is added as a component already
So I don't know why it's having trouble finding it
if(!EventSystem.current.IsPointerOverGameObject())
Found the solution
@wispy fjord lowercase b in body
omg I am so blind π€¦ββοΈ thank you
expect me to come back with more problems π§ββοΈ
so i want to have boundaries for my 2d game and what i did was I created a gameObject that has a boxCollider(trigger enabled) and made it so it filled my whole game.Now i was wondering how to make my player not leave this gameObject,this is the code I came up so far but I need something to make my player not leave this gameObject
i'm trying to create a line renderer from code but it keeps returning null? do i have to specify something or what
void Awake()
{
barrelPosition = new Vector2(0, 0);
tongue = new LineRenderer();
tongue.startColor = Color.red;
tongue.endColor = Color.red;
tongue.numCapVertices = 0;
tongue.startWidth = 1f;
tongue.endWidth = 0.1f;
tongue.SetPosition(1, barrelPosition);
tongue.SetPosition(2, barrelPosition * 2);
}```
Im trying to create a system that ups the cost of the upgrade evry time you buy, any ideas.
just.. add to the cost?
You should also configure visual studio. It should not say Miscellaneous Files at the top. Config instructions are pinned to #π»βcode-beginner
rb2d.velocity.Set(Input.GetAxisRaw("Horizontal"), 0); // doesn't move
rb2d.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0); // move
first time user here, trying to move stuff, why velocity.Set doesn't work?
@idle heron Vector2 is a struct. They are value types, and velocity gets basically copy of values.
so?
Set changes values on the copied Vector2 by value
you can get an intermediate Vector2 set it then assign back as a whole

myVelocity.Set(Input.GetAxisRaw("Horizontal"), 0);
rb2d.velocity = myVelocity;```
Also, you don't need myVelocity = rb2d.velocity, you can just initialize it to any other vector, like Vector2.zero
yes, this makes sense only when you want to additionally manipulate/use those values, not just set them.
π©²
i mean, rb2d.velocity is also an existing Vector2 so why can't I set it directly?

Because it's a property of a struct
And structs are not passed by reference
Rather by value
It does not get a reference to the Vector2 (velocity) to be changed, because structs only give their value not the object itself
So when you call someVariable.SomeProperty it returns a copy of the struct rather than the reference.
I'm full aware of the difference of value and reference, just don't see how is that the case in here

ok gotta you
what the hell dude, managed language is so confusing then
why does myVelocity.Set(Input.GetAxisRaw("Horizontal"), 0); work in the example Fogsight posted above?
myVelocity there is a local variable, that is present there, you can manipulate it.
while .velocity is not there at all, just its value
wait wait wait
rb2d.velocity.Set(Input.GetAxisRaw("Horizontal"), 0); // doesn't move
rb2d.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0); // move
in that case isn't the second line the exact same? you are only assigning the new Vector to "someVariable.SomeProperty it returns a copy"
Vector2 myVelocity is a local copy and we're modifying it whereas the dot velocity property will return a copy of velocity, which likely isn't what you want to modify.
If it was a field then the behavior would result in your/many's expectations.
It's the same difference when you are trying to change rb2d.velocity.x separately.
I think it's because of the new keyword Onigumo
You need to either construct new struct or create a local struct to change its values and reassign.
It's the assignment operation rather than method operation
How you should perceive this: ```cs
//If velcity was a field
var copy = rb2d.velocity;
copy.Set(Input.GetAxisRaw("Horizontal"), 0); // doesn't move
rb2d.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0); // move
yeah... I get how it works now and probably can just move on, but it just bugs me when I trying to think about how does it work under the hood
especially if you put it that way
Property would be prefer over direct access of fields in cases where polymorphism may occur; since they are basically getter and setter functions pointing to some local field..
Where override can be used on functions and properties but not fields.
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override
so the second line equals
Vector2 vec = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
rb2d.velocity = vec;
is that correct?
That should be fine, yes.
Difference would be you having a extra copy of vec sitting around till memory is freed; little to no performance impact.
ok now here is the part i don't get because then in that case it's like
var copy = rb2d.velocity;
Vector2 vec = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
copy = vec;
It's a tad bit different from what fogsight posted: ```cs
Vector2 myVelocity = rb2d.velocity;
myVelocity.Set(Input.GetAxisRaw("Horizontal"), 0);
rb2d.velocity = myVelocity;
You'll want to reassign the Vector2 to the velocity property; our original intentions.
yes but you guys said that's only a copy
var copy = rb2d.velocity;
copy.Set(Input.GetAxisRaw("Horizontal"), 0); // doesn't move
then no matter what i assign to it, it shouldn't affect the object at all
It would be the same as: ```cs
Vector2 myVelocity = rb2d.velocity;//Copy our velocity so we can manipulate it.
myVelocity.x = Input.GetAxisRaw("Horizontal");
myVelocity.y = 0;
rb2d.velocity = myVelocity;
You need to assign the copy back to the velocity property.
var copy = rb2d.velocity;
copy.Set(Input.GetAxisRaw("Horizontal"), 0); //Modify the copy of velocity
rb2d.velocity = copy;//Update our velocity
ok so you're saying "Set" is not assigning anything
It's modifying a copy; yes it doesn't do anything to Rigidbody2d's velocity.
Since you're just setting the velocity without regards to the previous values, you could just assign it directly; disregarding/not-caching the previous values: ```cs
rb2d.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
You would do the three part operation when you'd want to keep a particular component of the velocity: ```cs
//velocity before is { 1, 2 }
var velocity = rb2d.velocity;
velocity.x = input.GetAxisRaw("Horizontal");
rb2d.velocity = velocity;
//velocity after is { input.GetAxisRaw("Horizontal"), 2 }
Like the usage of functions getters and setters: mainly but not limited to differentiating access restrictions and polymorphism (inheritance with parents and interfaces)
Goes into OOP which may be beyond the use case of what you necessarily need but likely usefully for the game engine; never know what fields will be changed (behavior wise).
Ah, didn't cross my mind at the moment that you may have been referring to the Vector2 struct rather than the property behavior. It's a function of Vector2 and does what's implied. It isn't related to the access of the property as a method but the Vector2 struct and is working as intended. It's just unfortunate that it's modifying the copy-velocity's components rather than RigidBody2d-velocity's components.
can anyone help me out with my code. im trying to implement wall jumping and sliding into my game but its not working. this is the relevant area of code https://hastebin.com/oxijavawot.csharp
Should mention what's actually occurring and what's not.
oh, sorry
its not sliding down and its just sticking and when i click jump it boosts you in the y axis but has no visible impact on the x axis even if i crank up the numbers a lot
Any ideas on what to do?
@mystic wren Did you set the friction of the rigidbody to 0?
if you don't then it'll just stick to the wall when moving towards it
@tall current that fixed the sliding issue. thank you so much
any idea on the wall jumping issue
is it when you're jumping while "running" towards the wall, and it doesn't change your x axis, only y?
tldr; it goes up, but not right or left
yeah but when looking at the rigidbody info it shows a breif moment of velocity on the x axis
right, so, I've had to tackle this problem before
how did you fix it?
I believe what is happening is that, as you can see in your script:
FixedUpdate handles horizontal movement.
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
this changes your horizontal movement, as you know.
The problem is, that when you're walljumping, this pretty much instantly overrides any other forces, the reason for your Y axis being correct is because you're setting it to rb.velocity.y, but the X is set to the input * movementSpeed.
When walljumping on a wall to the right of you, input = 1. Therefore the code above moves into wall instantly after jumping.
tl;dr
The horizontal movement instantly overrides the walljump movement.
any way on how to fix that?
plenty of ways to fix it, yeah.
Can you think of anything that'd work?
probably but its 3am here and i should be asleep but I cant sleep but am barely able to write a full sentance
so I can try to tommorow
do you mind if I dm you if I cant figure it out for your help
Hi
I have a question
Do I need to know 2 dimension physics? And how can I learn coding it?
Do I need to know driving a car? Well yes if I want to drive it π so what do you mean @flint peak Youtube got like tons of tutorials on how to start coding as well as how to start physics2D
@craggy kite do you suggest any yt channels?
@flint peak Not really, just look for not too old ones when it comes to Unity specifically, as things change in Unity UI, but besides that, there is nothing wrong to go for for the start. I mean, Unity itself as alot of unity tutorials that will help you get started
@flint peak Seriously, put some effort into reading... its right at the site i linked
Ok thx :)
Hello peeps. I'm making a gridlayout for inventory (so I have a bunch of square cells) and I want the number plate on this to appear in front of the next cell rather than beehind it. How would I achieve this without changing the grid's starting position? (as the starting pos needs to be top left so that items appear in the correct order)
every number plate is a child of its corresponding cell
there you are again π
;D
You could add a canvas to it and override sorting then
yep
yw π
I'm gonna have to start paying you at this rate lmao
π I am here anyway in my own project, hopping in and out, all good π
Crafting system dun
Updates, right now! π
shall put in works in progress π
Would anyone be willing to give me some articles or videos or personal help on generating multiple groups of bricks in a certain area with the groups separated from each other?
Hi, I'm new to Unity. I have sprites for a 8D character movement, and 8D gun sprites, so I have character movement nailed, but how should I approach doing the gun? What I did was create a still animation for each graphic of the gun, and then use a blend tree to switch animations based on angles, however I need some offsetting for each gun position and I have no idea how to approach the problem
issue for refence
in the bottom pic the gun needs to be moved NE
I'm still stuck on this as I have no idea how to approach the problem, anyone able to help? If you need some more info lmk
The easiest thing would be to just use the same size/pivot as the character and create the 8 directions. Then you simply overlay it on top of your character.
That would also allow you to control how different guns look in the different directions.
So I am using free assets, should I like change the canvas sizes of the gun assets im using?
and so move the gun left/up/down/right in the asset?
also is using still animations and a blend tree a good way of rotating the gun? or maybe a better method?
You usually don't want to use blend trees with snappy 2D art, because there's nothing to blend.
I used blend trees, as when I calculate angle of mouse from x-axis I can switch the directions easily
and I dont know a betetr way to do it, how would you recommend?
Right, well if that's working for you, then keep at it.
As for the gun, you can just give it it's own animator, and just manually position it with each animation?
Using free assets is going to be a challenge though, but that's the cost of it. π€·ββοΈ
Yeah this is for a small project and Unity has a learning curve for me lol
Ill try messing with the canvas, dont want to spend too long on small graphical stuff until most the structure of the game is built
ty π
Hi, I've been trying to do this for a while now so if anybody could help I would be thankful. My situation is I want to change the opacity of a tilemap when a player walks into it, I've got it working with the sprite renderer but not for the tilemap. I want to be able to change the color of the entire tilemap at once as well. Any Thoughts on how to do this?
doesn't the tilemap component just have a color property??
@light silo
as for knowing if you are on the tilemap, you can probably just check if the player's position (rounded to a grid position) has a tile that isn't null
using GetTile
The tilemap component does have a color property and thatβs my issue, I canβt change that in the script. Also sorry Iβm very new to this so I donβt quite understand everything @plush coyote#9329.
Is it overlapbox meant to not interact with colliders that have isTrigger = true
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
The last parameter defines if triggers are considered. By default, it ignores triggers.
Okay, seems like it worked. Before it would not count any collider that had isTrigger = true as a hit
how to group parts
@void jetty Don't cross post.
ok
is there a way to cross fade between two sprites. im trying to show something like an engine bell becoming red hot after firing for a set amount of time
Hey, I have a question
Can I send here the unity forum post?
I've been the whole day trying to solve it and nothing :c
@cyan smelt you could use a shader that combines them all in one Z depth, but thats just an idea, cant help you writing that custom shader now
U have some kind of guide or tutorial about shaders to orientate me along it? I've never worked writing shaders : s
@craggy kite
google shader graph for unity, I got no tutorials like at hand
is this an script error? i don't get how fix it
Where does this come from?
like it should tell you in console where the error comes from
does anyone know the best way to switch a player between sprites, like an idle shift back and forth kind of thing?
Anyone know how to make a bullet destroy itself after it impacts something else? @ me
Assuming you're moving it with a rigidbody, stick a collider on it and a simple collision check:
void OnCollisionEnter2D(Collision2D col)
{
Destroy (gameObject);
}
Of course, eventually you'll want to consider object pooling the bullets for performance reasons, but the above is as simple as you can make it.
Idk if this belongs here, but I have some objects with box collider 2Ds in a canvas, and I'm trying to make them draggable but it's not working
here's the UI canvas thing
and this is the code:
(btw the code is on each of those wires)
idk if i set it up wrong but it's not debugging that drag message nor doing anything at all which leads me to believe that it's not recognizing the mouse dragging it?
hey guys, when i move horizontally my character sometimes get stuck between platform and ground tilemap collider. platform uses Box Collider 2D and the ground uses Tilemap Collider 2D. any ideas how to fix this?
I tried combining Box Collider and Edge collider on character which almost worked, but new issues came to light where the Edge collider would go inside the Tilemap Collider causing moer issues than before. help is much appreciated!
here it works fine
but right here it doesnt work in a consistent manner, i dont get it..
yeh, it is
Is that a box collider 2d?
oh, you wrote it there, sry
Did you try to increase the edge radius just a bit? @wide ridge
no, ill give it a shot
so far it looks good! hopefully itll remain that way lol
π Yeah the collision thing sometimes does weird things.
Anyone know why this is not working. Whats suppoded to happen is when the bullet hits an object it will get destroyed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
void OnCollision2D(Collision other)
{
Debug.Log("Collided");
Destroy(gameObject);
}
}
what is not working
If I was having your error, what I would have said is:
"I defined a function called void OnCollision2D(Collision other). I expected this function to be automatically called whenever the gameobject collides with anything; however, the function never seems to get triggeredβnothing from it gets printed to the console and the bullet continues to exist upon colliding with other objects. Does anyone know why?"
This means less guessing
@tropic inlet guess what
wat
he fixed it π
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D col)
{
Destroy(gameObject);
}
}
thats all that is needed
2 freeaking lines
well you just needed to add the 2D to the Collision2D Parameter...
and Enter
i figured that out eventually
oh yeah π
@still tendon
#πΌοΈβ2d-tools message
I literally told you that.
hello death
hello death im hell
I have these planets
And I want to make them move towards random places like in this video
In the second episode of this "How to make an IOS/Android game in UNITY" we will program the core gameplay using C# !
By the end of this tutorial you'll have a working, playable game on your hands, so get excited :D !
Support me via PATREON : https://www.patreon...
But the script he shows doesn't work
And I can't find anything similar
What should I do?
how do I show my code in discord?
@hearty granite <#π»βcode-beginner message>
Is there a video anywhere that covers the code in 2D Game Kit?
i need help with something, i want to do an AI like the space invaders enemies, but i dont know how to make they move one direction and then the other in a certain point
sounds easy, but i have problems, this is my first project ;0;
please help
i want this to return the collision2d contact normals every frame, this script works sometimes but its very inconsistent. any ideas why?
You aren't returning anything per frame but if you're asking about updating value per frame, it is. Unfortunately physics frame (I'm assuming that's where collision info is being updated) isn't sync 1:1 with the standard update frame; hence why you might possibly be having undefined behaviors.
so i should use OnUpdate instead, or doesnt it matter?
Doesn't matter (I'm assuming you're using new input system).
On_ aren't the same as without the On.
I'm assuming you're sending messages with new input system.
i'm using playmaker
its weird, cus i changed it to OnUpdate and now it works, but it previously worked with OnFixedUpdate and suddenly not on runtime
u can see the vector3 bottom left changing
I do not know anything about Play Marker unfortunately.
i found a different approach to do what i want. either way thanks for providing your help!
https://hatebin.com/nqvyceaszi why is my object not moving forward when pressing W?
im getting this error in unity
In my 2d game I have a object follow my mouse but there is a little bit of delay anyone know any fixes
can someone help me??
pretty much
when i move i would like my charcter to flip to that postition
that im moving at
can someone give me a movement script??
Nope
help
Cant help with that
You're trying to access an object you've already destroyed.
May need to rethink the logic here.
Does anyone know how to properly set the tangentmode of a point of a spline to be continuous?
i do this now, and it actually changes the tangent mode, but it does not seem to have any effect
As you can see, the tangent mode is changed to continuous, but only after i first change it to a different mode, and then back, it works
how can make a surface that look like undertale
like no gravity action
like at the main caracter
hey i need help
im getting this error in my script
https://paste.myst.rs/lzvqtrww this is my script btw
a powerful website for storing and sharing text and code snippets. completely free and open source.
You are declaring movement in FixedUpdate()
its out of scope for Jump()
declare it at the top
ok thx
np
uh im a beginner as well but sure i guess
just got one lmao
when you say declare it at the top do you mean like this?
because im still getting the error
did you save the file
yw
Ok so i have a image on my canvas and i want it to always point the direction the main object is moving but i cannot get it to function correctly. this is the code i am currently using rocket refers to the rigidbody of the object i am tracking movement for
velocity.Set(rocket.velocity.x, rocket.velocity.y);
transform.right = velocity;
hi i need help
i followed this tutorial on how to make a 2d platformer last night
and i saved my project before i closed the thigny
and now when i open up the project again
all my assets are there
like my coding stuff and the asset art i was using
but the game itself is gone
non of the tilemap's or player's or anything
only the camera is there
and idk what i did
(i used this tutorial https://youtu.be/SN8CKFlsjPA )
This tutorial series will show you how to create and publish a 2D platformer in Unity. In this intro video we will be covering how to download Unity and open our project.
Subscribe: https://www.youtube.com/channel/UCpneKOUKQeN7idt1r67vXMA?view_as=subscriber
Facebook: https://www.facebook.com/pg/humbletoymakergames/about/?ref=page_internal
...
@heady bone Did you open up the wrong scene?
i dont think so
i just opened it from the unity hub thingy
and the game is gone
and in the scenes folder its just a samples scene
thats the same exact thingy
(by same exact thingy i mean theres just nothing)
did u forgot to save your scene the last time you modified something?
i make a habit of pressing these 2 buttons about 17 times before i close unity
idk. It should be there somewhere
click this
and click scene
the button wit hthe shapes
and it will find all scenes within the project
Click them both
demo is a scene, yes?
yeah
show me
Then it looks like you didnt save
just the two buttons i marked is what you should press
You said you spent a night
like 3 hours
it might suck, but 3 hours isnt anything to stress about
i said i did it last night tho
it is to me
ive never done anything like that before
you've done it once, will take half the time to do it again π
true
just saddd
i like unity tho
its nice
but on the bright side once i get out of this sad
the tutorial guy who i watched will hopefully have a new video out for the tutorial
so thats nice
π
oh quick question
how do you make custom art stuffs
for unity
like a flag or something
to go to another level
Draw it i guess
i didnt know if there was a special process sorry
Errr, Or do you mean applications to draw, or places to get these things?
Aesprite is good, but it costs
opengameart.org or itch.io for pixel assets
Piskel is a free browser pixel art program. But obviously its not going to be greate
but i like my kidney's
13 year olds can absolutely get jobs
oh
Maybe not right now... with the state of the world
I did a paper round at 13 till i was 17
nice
Delivering papers across my town
i thought you had to be 16 thats all
What sort of game are you making? i have some sprite sheets that might be useful. But they are very... specific
and im not the best drawer
idk i kind of want a decently long sorta like
story fighting game
but linear like mario
and sorta like rogue assasin or whatever
that flash game where you run in a straight line and fight
i dont qutie know
These are what i've made. they're plastered with Sample so if you want anything, i can jsut send you the proper sheet you can tinker with
okie dokie
they're pretty good
just not the style im really wanting
nothing against you
No worries, i made these couple years ago π
there... is a rogue assassin character i used before, let me find it
okie dokie
oh now thats cool
so if i download lots of stuff of the unity asset store
and i forget the name of it
is there a little area where i can find all my downloaded foshizzle?
if its from the unity asset store, it will be in your "my assets" folder
on the page
okiely dokiely
thanks for the help
np
ur the best
@still tendon because the "turret" is in the wall
How do you expect it to move if it's phyiscally blocked.
Same as trying to close... A closed door
hey i want snow that piles up in a 2d platformer
already have particle system to show its snowing
but i want the ground to pile up with snow
which you can walk on and it destroys/compresses with like rigidbodies maybe?
any idea what i could use?
oh it should run decent on mobile too
Particles that collide and mobile are not the best friends @still tendon
You can still call particles to work with collisions, if you haven't checked that. That way it can collide with your player and itself
Hi, So I want to make a wave system. I did it but it's not infinite (What I want to). So I want to know how to make it infinite, and adding more enemies every wave .
Here's the code https://paste.pythondiscord.com/anematebew.csharp.
It's long so I put it here.
You will have to make up some algorithm that just multiplies on and on. @slate epoch more of a logic thing than an actual problem. You can check other games on how they do it, just observe some time in the game or google for mechanics on that game. There are different approaches, but in the end, its some kind of simple math to keep the user in the infinite task loop π
ok thank you
Has anyone here editor the spline of a spriteshapecontroller through code?
im trying to change the tangentmode of a spline point to continuous, which changes the type, but doesn't actually have any effect in the game itself. so it changes the type in code, but doesnt work
I guess you have to set it back to the character you are modifying @livid flare
Hello, I'm having an issue where a player character is recognizing a collider, but if I issue a diagonal input, the player will step into the collider and get stuck. The character is using a capsule collider and the wall is using a box collider.
https://hastebin.com/rudovesuco.csharp
maybe you need to use continuous collision instead of discrete, i think its on the rigidbody
Thank you for the help, it turns out I didn't normalize the original initialization of moveDir. That solved my issue
when i use my transform.LookAt code, my gamobject decides to disappear, how can i fix this
yea, that's the thing with 2d
u gotta watch out when u use transform.LookAt
One thing u could possibly try is use
Quaternion.LookRotation(...).eulerAngles and zero out unnecessary axes (you only rly need the Z rotation for typical 2D, as far as I've seen)
or, uh, even easier,
just directly assign to either transform.right or transform.up
GameObject a;
GameObject b;
a.transform.right = b.transform.position - a.transform.position; //a's right should now be facing b
//formula for a direction vector from point A to point B in general is
//(B - A).normalized
//But, in this case, normalizing doesn't seem to be necessary
@wanton laurel Disappear you mean it rotates around, right? You should specify on what axis it should rotate then, so it will not rotate around the Y axis.
Dont ask to ask, just ask π
xd
the problem is the 2 route here
how do i make the player choose to go one way and only one way onward
i have a waypoint system too
Okay, whats the question actually, as we are in coding. Whats the waypoint system, unity build in one? Or custom? And where are you with your code about that part of deciding?
custom and i really don't know
That sounds like a bad start to help honestly π
oh no
so here 's the script for follow the path https://pastebin.com/XNpkrvFw
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how do a make the soil automatic repleace soil to soil whit grass
Hello I'm trying to select a tile in a 2D chunk with negative positions. But I can only have positive coordinates because arrays only work on positives. So I have to convert the negative positions to positive positions. Here is what I do. I only do substractions to select the precedent chunk if the selected coordinate is negative.
It works now I solved the issue ! π
function name {
...
}
nice compact style
hey, I am trying to make a cube that can be cloned and the clone can be picked up but the problem is that when I change the box collider on the new cube it does it on the original. this is because I have the original cubes box collider linked. I think the problem is using this line instead of something else to detect the BoxCollider2D of the object in-front of it: public BoxCollider2D boxCollider any suggestions on what to do? if needed I can post the code
@mystic wren don't quite understand the issue, you have GameObject with a script and collider and you clone it ? and the script in the clone references the collider in the first object ?
@split walrus Let me try this from the top so I can try to explain better. I have 2 objects. Object 1 is the player, object 2 is a cube. When I pick up the cube using the player I want to set itβs collider to disable. And to be held in the players hand. The problem is that when I clone the cube which would create a 3rd object, when I pick it up, it makes the original cube have no collider and not the new one. Does that make any sense?
you do all this logic from script attached to player ?
the cloning script is attached to the cube
and the collider disabling ? I feel like you reference 1st cube and when you instanciate 2nd you should newCube.GetComponent<BoxCollider2D>() to get reference to new one
heres a video of it
is there any way to reference both at the same time, maybe by like referencing the layer or something
could you send the code where you disable the colider at ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabObjects : MonoBehaviour {
public bool grabbed;
RaycastHit2D hit;
public float distance=2f;
public Transform holdpoint;
public float throwforce;
public LayerMask notgrabbed;
public Transform height;
public BoxCollider2D boxCollider;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.B)) {
if(!grabbed) {
Physics2D.queriesStartInColliders=false;
hit = Physics2D.Raycast(height.transform.position,Vector2.right*height.transform.localScale.x,distance);
if(hit.collider!=null && hit.collider.tag=="grabbable") {
grabbed=true;
boxCollider.enabled = false;
}
//grab
} else if (!Physics2D.OverlapPoint(holdpoint.position,notgrabbed)) {
grabbed=false;
if (hit.collider.gameObject.GetComponent<Rigidbody2D>()!=null) {
hit.collider.gameObject.GetComponent<Rigidbody2D>().velocity= new Vector2(transform.localScale.x,1)*throwforce;
}
}
}
if(!grabbed){
boxCollider.enabled = true;
}
if (grabbed){
hit.collider.gameObject.transform.position = holdpoint.position;
}
// Debug.Log(grabbed);
}
void OnDrawGizmos(){
Gizmos.color = Color.green;
Gizmos.DrawLine(height.transform.position,height.transform.position+Vector3.right*height.transform.localScale.x*distance);
}
}
can you see that?
yes
ok
@low blade You'll need to design some branching path logic into your waypoint system but without knowing the context of the waypoint script it's tricky to help
One example you'll need to change is your waypointIndex int for discerning the next waypoint, you could instead have a component on each waypoint that knows what the next waypoint is, then instead of using the index you just use the nextwaypoint value of the current waypoint
Then you could give each a LeftWaypoint and RightWaypoint
And if the left/right waypoints aren't null then potentially use them instead of nextwaypoint but you'll need a way to input whether to use forward/left/right
@mystic wren if (hit.collider != null && hit.collider.tag == "grabbable") { grabbed = true; boxCollider = (BoxCollider2D) hit.collider; boxCollider.enabled = false; }
where you raycast and get back collider .. set your collider reference to that collider that you get from raycast it should be correct cube
but how would I do that if the cube isnt created when starting the script
it should do that when you press the button to pick the cube up
sorry if dumb question
Dumb questions don't exist
low self esteem does tho and I have plenty of that
:D don't worry
just add this line : boxCollider = (BoxCollider2D) hit.collider; in that place where I showed you in the code
and lets see what happens
π so it works I assume
yea sure
its hard for me to explain in words so heres a video of the problem
basically, holding the cube messes up the pressure plate
its 41 seconds for me :D
That was just my Discord bugging or something
the way its detecting a object is by using 3 raycasts on it and any combonation of raycasts to detect if somethings on it
so pressure plate uses raycasts too ?
yeah
hmm and it doesn't detect button after you held it and then dropped, but it works okay before that ?
hmm I would suspect that button checks for some bool or other condition that is being altered when you pick the cube up but is not reset correctly back when you drop it
can't really tell more without looking at buttons code :)
oops, forgot to send code
1 sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteChanger : MonoBehaviour {
public SpriteRenderer spriteRenderer;
public Sprite spriteA;
public Sprite spriteB;
public Transform Point1;
public Transform Point2;
public Transform Midpoint;
void Start() {
}
void FixedUpdate(){
float laserLength = 0.2f;
//Get the first object hit by the ray
RaycastHit2D hit1 = Physics2D.Raycast(Point1.transform.position, Vector2.up, laserLength);
RaycastHit2D hit2 = Physics2D.Raycast(Point2.transform.position, Vector2.up, laserLength);
RaycastHit2D hit3 = Physics2D.Raycast(Midpoint.transform.position, Vector2.up, laserLength);
//If the collider of the object hit is not NUll
if (hit1.collider != null
|| hit2.collider != null
|| hit3.collider != null
|| hit1.collider != null && hit2.collider != null && hit3.collider != null
|| hit1.collider != null && hit2.collider != null
|| hit1.collider != null && hit2.collider != null
|| hit2.collider != null && hit3.collider != null) {
spriteRenderer.sprite = spriteB;
} else {
spriteRenderer.sprite = spriteA;
}
Debug.Log(hit1.collider);
Debug.Log(hit2.collider);
Debug.Log(hit3.collider);
//Method to draw the ray in scene for debug purpose
Debug.DrawRay(Point1.transform.position, Vector2.up * laserLength, Color.red);
Debug.DrawRay(Midpoint.transform.position, Vector2.up * laserLength, Color.green);
Debug.DrawRay(Point2.transform.position, Vector2.up * laserLength, Color.blue);
}
}
is there any reason you don't want to use unity's trigger system for this ? would simplify everything a lot :D
ah, you didn't know, I see ;D .. np, let me give you small example how to go about it, just a sec :)
ok
some things just dont cross my mind, especially since I do my best code at 2-3am and its 4pm rn
yeah, there are a lot of things going in unity :D, takes time to get used to everything :)
yeah
I was really intimidated by how you had to add components to everything and had to create custom scripts
well, you have to think in components, its bit different architecture than say traditional OOP way of coding
yeah
but I think it makes at least prototyping much faster when you can just slap components
oh I see, never had a chance to try arduino unfortunately
they are really fun to use for hardware prototyping
as for trigger stuff here:
you need any 2D collider on your CUBE and rigidbody2D
then you'll need collider2D on your button
and check the Is Trigger checkbox
and script attached to button :
using System.Collections.Generic;
using UnityEngine;
public class PressurePlate : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Sprite spriteA;
public Sprite spriteB;
void OnTriggerEnter2D(Collider other)
{
spriteRenderer.sprite = spriteA;
}
void OnTriggerExit2D(Collider other)
{
spriteRenderer.sprite = spriteB;
}
}```
on triggerenter will fire once when cube's colider enters button's collider .. when collider is market as Trigger it allows other colliders go trough it it just sents notification to scripts attached to same game object
good luck with that ! :), I gotta go now, see ya!
Is there any good tutorial on how Canvas works? I'm setting a child GameObject's transform.position in code and it seems to multiply the resulting position by some unknown factor
the gameObject has a bunch of RectTransforms within it
@main narwhal I don't know about tutorials, but RectTransform has helpers for positioning in the context of a Canvas: https://docs.unity3d.com/ScriptReference/RectTransform.html
yeah I figured it out eventually
Basically if you want to position canvas elements on a canvas you just need to give it a rect transform because I have no clue what relation normal transform.position has
to canvas position
Yeah, it's pretty opaque
I try extremely hard to not write any code that interacts with canvas layouts
How do you do UI then?
I use the built ins
I mean the actual laying out of things
I rely on the groups and fitters etc
Anchors
Obviously I wire up event handlers and stuff that modifies text and materials
how can i rotate something towards something else but only on the Z axis
Hm, that's actually kind of tricky. Looks like sometihng like this might help
static Quaternion XLookRotation2D(Vector3 right)
{
Quaternion rightToUp = Quaternion.Euler(0f, 0f, 90f);
Quaternion upToTarget = Quaternion.LookRotation(Vector3.forward, right);
return upToTarget * rightToUp;
}
Then you can just do the rotation in the normal way
var direction = target.position - transform.position;
transform.rotation = XLookRotation2D(direction);
Is that what you mean by "rotate towards"?
like LookAt but only for the z axis
Yeah, that'll do it.
I mean, you can always just set transform.right
var direction = target.position - transform.position;
transform.right = direction;
That should work
Might get weird when you're looking up though, I'm not sure.
I think the first solution will be more robust (assuming that stackexchange answer was correct)
Anyone who know of any well made wandering script i can check out? i'm doing a top view and i cant seem to find any wander tutorial where the character moves smoothly around
Anyone have any suggestions on how I could go about using a tilemap with a rule tile, where certain tiles will have "alternate" variations. For example, holding shift will turn a stair tile into a slope. But still ensure that either the stair or slope behave the same way with respect to all the other rules setup in the rule tile.
I was thinking a similar interface to the rule override, where you basically behave alternate sprites in an array you could cycle through.
Not sure if there is already something that exists in the package or if I'll have to do something custom.
hey guys
so i'm currently making a board game
so i added some like penalty on the slot
how can i do a check to see if the character has landed on that spot or going to the slot above that spot
so you know not activate that penalty
Did you try just making a simple collision check?
Maybe show your code, so we know what yo are doin
yea
{
if (col.CompareTag("Trigger1"))
{
QuestionPanel.SetActive(true);
Debug.Log("Trigger");
}
Did you debug.log the comparetag, does it Trigger?
yes
So what are you struggling with? π
it activate the panel great
but
when the character go above(or to a different spot) is still showed the panel
if you roll a six but the slot is 5 its sill show the panel regardless
add else what disables the panel
OnTriggerExit2D then? @low blade
also you should use codeblocks instead: ```cs
code
```
but it still show the flash of the panel and then dissapear
i want it to be nothing at all
We're trying to create a node.js c#(unity) game(using socket.io).While Adding players and emitting data in a room, We got an RangeError: Maximum call stack size exceeded error.
Whole Error:
internal/
Can someone help with this
this possibly means something like this (in js): ```js
function x(y) {
return function(y);
}
x(50);```will throw maxium call stack size exceeded
so re-check all your recursion functions
@still tendon ^^ pong
oh thank you
I can't seem to get the Animation component to work for sprite animation.
I have player_anim_idle.anim, which I created via stringing together a series of sprites in the animation time line window (the one you open by pressing CTRL + 6).
Then I have a GameObject with a:
> SpriteRenderer component (with the "Sprite" field set to some sprite called idle_0)
> Animation component (and the "Animation" field is set to player_anim_idle.anim)
For the animation component, "Play Automatically" is checked.
But during gameplay, the animation component doesn't seem to be doing anything. All I see is when I look at my player mid-game is the sprite idle_0.
No animation of any sort is occurring. It's almost as if the Animation component isn't even there.
This problem doesn't exist if I use the animator, but the Animation component seems to have a simpler interface.
Nonetheless, for my 2D sprite-based game, I'm tryna create some system that'll allow me to do, like:
public void PlayAnimation(AnimationClip clip)
{
//...
}
public AnimationClip idleAnim; //set in inspector
public void Start()
{
PlayAnimation(idleAnim);
}
If anyone knows a way to do that, lemme know
k thx bye
If there was an immediately obvious way to create states and transitions for the animator component entirely through C# code, I'd be able to work with that, but I can't seem to find member functions for that in the docs.
Oh, interesting:
this looks relevant
How can you get the position of a collision enter with the collision is with a tile?
for me, it always returns 0,0,0
position of the tile?
is normal that a 2d camera looks like this?
you can change it from orthapedic to perspective
Hey all! I'm new here. I've been tinkering with Unity for a couple months, the 2D side of things to be exact. I'm right now facing a problem with Colliders and smoothed movement with SmoothDamp: when my character collides with a boundary, it kind of "gets absorbed" a little and lags a bit when i try to move away. Removing the SmoothDamp removes the problem entirely. So: is there any way I can keep the SmoothDamp kind of movement while fixing this issue, without having to detect all collisions (triggers) by hand?
Update: seems that the little "bounce" is a default behavior of colliders and rigidbodies, but having SmoothDamp enabled makes that small movement take a very long time. Any parameters I may tinker with?
@still tendon are you applying the damping before ir after the physics?
I am updating the transform position at the beginning of fixedupdate based on the input axis which is plugged in the damping together with the previous value and a fixeddeltatime*speed parameter
Physics are handled outside of code atm
Just what are you attempting to achieve with the damping, precisely?
Does it need to happen in fixedupdate?
For a lot of situations you only need to apply input smoothing once per frame.
Also, if you are using delta tine inside of fuxed update that coukd cause weird behavior.
I thought it would make the movement more physical for it to have a little weight (itβs a guy with a glider sort of).
Itβs in fixed update because thatβs where Iβve been updating the movement so far, it kind of made sense since Controls should be kind of consistent in time and not tied to framerate i suppose
Delta time is meant to compensate for variable frame rates in update, whike the rate of fixed update is as close to fixed as possible.
Maybe i could achieve similar results by using the physics to govern movement? Instead of adding a delta movement each update
Thank you for your interest by the way, feels good to speak with somebody π
Messing with position directly will mess with physics too, yes.
I think i need to review the way i process my input updates and subsequent movement i guess
Do you by chance know some good example about this?
Um, not offhand. Just avoid the brackeys tutorials, they will mess you up :3
Thatβs news to me hahah are they really that bad? So far Iβve been trying to figure out as much as possible on my own, trying to build my own workflow but itβs all trial and error
Iβm doing a super basic and simple project on purpose
Well, they focus on high production values rather than actually teaching hiw to do things correctly.
And while he was particularly active half the questions in here started wuth 'I'm trying to follow this tutorial and...'
Starting simple is definitely a good idea!
Do you think applying the smoothing directly on the axis data could achieve anything? Right now I think it gets messed up because the smoothingβs starting value is taken directly from the transform so it also applies to the movement caused by colliders and stuff
First things first: in general do you think I should apply smoothing to the movement or to the input values?
Like which one is preferable if the objective is to have a smooth motion that feels like itβs accelerating and decelerating left and right?
One thing to note is that unity can apply input smoothing itself
And if you are using physics forces to move then acceleration and deceleration will happen normally.
If you're using physics there shouldn't be much need to apply smoothing to the motion itself.
that's definitely something to think about, whether it makes sense to go about it in the current way or if id better move the controls to the physics engine.
Thank you for your insight! Goodnight
I have a question about 2d movement, if you use this code to dictate your characters movement:
myRigidbody.MovePosition(transform.position + change.normalized * speed * Time.deltaTime);
How can you check your rigidbodys current movement speed? Checking velocity with this code:
myRigidbody.velocity.sqrMagnitude
returns a consistent 0, as I'm assuming the "MovePosition" code isn't giving the rigidbody velocity, but more so just teleporting a short bit every time.
I've tried getting a previous position and comparing it to the current position of the rigidbody to see if they are equal, i.e. the rigidbody is not moving, but this has its inconsistencies especially when dealing with collisions and the like. If I need to be more descriptive please let me know, and thanks in advance!
i think moveposition is independent from Rigidbody.velocity
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
Moves the kinematic Rigidbody
Based on my tests it seems like it, is there any other way to check if the rigibody is moving?
@ivory tapir moving rigid body with transform sort of defeats purpose of rigid body, there has to be better way to do what you want to do. Either moving the object using physics or if you don't need physics you can calculate velocity yourself by storing position of your transform and comparing that position with new position next frame
to check your Rigidbody's speed, you can always reference myRigidbody.velocity
using System.Collections.Generic;
using UnityEngine;
public class VelocityMeter : MonoBehaviour
{
public float velocity;
private Vector3 _lastFramePosition = default;
void Update()
{
var distance = Vector3.Distance(_lastFramePosition, transform.position);
velocity = distance / Time.deltaTime;
_lastFramePosition = transform.position;
}
}
``` here's example how to get velocity of transform .. it will work regardless of rigidbody
I figured out a decent solution to my problem^
this SimpleAnimation component is better than Mecanim tbh
And the way you can add AnimationEvents via code is so convenient
//Attack is some Serializable class
//attacks is a public Attack[]
foreach(Attack atk in attacks)
{
AnimationEvent evt = new AnimationEvent();
evt.time = atk.clip.length;
evt.functionName = "OnAttackEnd";
atk.clip.AddEvent(evt);
}
doing this manually would be soo lame
Appreciate all the help guys, ended up using @split walruss solution and it's perfect. Thanks!
you're welcome! :)
why of this?
https://gyazo.com/7aac55c80e09a815d75ad2ed4c5a6db5
this happen when i move
never got an answer, what is the way to get the time since the last time a system ran
@still tendon DateTime class, probably
doesnt work with parallel jobs I dont think
hi, i have a question. i am opening a chest in my game by pressing spacebar, which shows some text on the screen. i also hide this text using spacebar. the problem is that unity instantly hides the text as soon as it is shown, probably because it still detecs spacebar as pressed. How do i fix this?
if(Input.GetKeyDown(KeyCode.Space) && playerInRange)
{
animator.SetFloat("chestOpened", 1);
if(dialogueBox.activeInHierarchy)
{
dialogueBox.SetActive(false);
}else if(chestOpened)
{
dialogueBox.SetActive(true);
dialogueText.text = dialogue;
chestOpened = true;
}
}
is there any way i can set a minimum time for the text to stay onscreen?
GetKeyDown will only be called once, so it's not that.
weird, because the dialogue box disappears immediately, but the chest animation happens
Do you want it to autohide after the chest opens up? Or only when you press Space again?
when i press space again
Is there an animation or any additional code on t he dialogueBox object?
no additional code, and the only animation is setting another sprite
Right. Well step one to debugging would be to put a Debug.Log inside the if statement for pressing the space bar.
And seeing how many times it's called when you press Space.
hmmm, looks like it doesn't appear in the first place
alright, it has been fixed, thanks!
i forgot my ! before chestOpened in the else if
Those are always tricky to find, nice job.
Are you using the new input system by chance?
Actually, you aren't, if you're using GetKeyDown.
In that case, your best bet would be to use a bool on your controller which you flag true/false based on if the player is in dialogue (or "busy" otherwise). And then check against that before allowing the player to make input.
hmmm, i followed a Brackeys tutorial so i have no clue which i am using
Original then.
So you would create something like bool isPlayerBusy = false;
And when you begin dialogue, or opening a chest, you would isPlayerBusy = true;
void Update()
{
if(dialogueBox.activeInHierarchy)
{
Movement.x = Input.GetAxisRaw("Horizontal");
Movement.y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal", Movement.x);
animator.SetFloat("Speed", Movement.sqrMagnitude);
}
}
gonna test this
void FixedUpdate()
{
if(dialogueBox.activeInHierarchy)
{
rb.MovePosition(rb.position + Movement * moveSpeed * Time.fixedDeltaTime);
}
}
Yeah, exactly, you check the state of the game before allowing movement. Though, keep in mind, if you plan to add other times to lock the player, you're going to get a pretty long IF statement.
there's also this whoops
but these are different scripts
can i set a bool from another script to false?
You can call any public functions and modify any public variables on another script as long as you have a reference to it, yes.
how do i reference it? do i reference the object the script is on?
You can reference objects in a variety of ways.
Option 1:
Create a public variable of it public MyScript reference; and drag the object with that script into it, in the inspector.
Option 2:
You can use FindObjectOfType <MyScript>(); and cache a reference in your code
Option 3:
If the reference you want to make is on the same object, you can use GetComponent<MyScript>();
Option4:
If the reference you want to make is a child object, you can use GetComponentInChildren<MyScript>();
should i name it reference? or after the gameObject?
error CS0246: The type or namespace name 'MyScript' could not be found (are you missing a using directive or an assembly reference?)
You of course would replace MyScript with your component name.
is it possible to do an interpolated rotation?
If so then how
Did you put a second camera with dont clear or something like that on it?
yes it was on here
My top 5 fun ways of breaking the Unity game engine. Prepare to see some crazy glitches, fractals and illusions while perhaps even learning a thing or two about how rendering in video games actually works.
0:00 - Intro
0:22 - Disable Clearing
2:08 - Everything To Rigidbody
2:54 - Extreme FOV
3:58 - Double Camera
5:52 - Inside Out
6:15 - Render ...
the second camera are disabled
you need to enable clearing
click on that https://youtu.be/kJrnWvf494w?t=39
My top 5 fun ways of breaking the Unity game engine. Prepare to see some crazy glitches, fractals and illusions while perhaps even learning a thing or two about how rendering in video games actually works.
0:00 - Intro
0:22 - Disable Clearing
2:08 - Everything To Rigidbody
2:54 - Extreme FOV
3:58 - Double Camera
5:52 - Inside Out
6:15 - Render ...
got it?
in 2d this option is not avaliable
most of people help in #π»βcode-beginner
Wdym? Any camera should have the option. Take a screenshot of your cam.
i rollback the default config of unity and works normaly, but with the blue instead this color
It's the background type setting. You can change the color there too.
where?
Can someone help me? Im doing a top down game, and I want the player to look at the mouse, and it works fine and everything, but when I add cinemachine or just make the camera follow the player, then the player start "vibrating" or "wabbling" Code: ``` void Update()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate()
{
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}```
Does anybody have any good tutorials on sprite ordering? I'm struggling to get some sprites overlapping how I want them to and i'm pretty new to Unity.
or perhaps somebody here can point me in the right direction?
The issue i'm having is like this: if I have two sprites on the same "order in layer" i want it to sort them from bottom to top. So when a sprite is "lower" than another, it will be rendered on top and when higher it will be behind.
I managed to find a thread with the answer in, if anyone else gets this issue and sees this its here:
https://answers.unity.com/questions/574217/moving-pivot-point-for-a-2d-sprite.html
You can change the sorting axis by going to Project Settings > Graphics > Transparency Sort Axis
Change the values to (0, 1, 0) , which will sort on the Y-Axis for sorting groups.
Hey guys
Why is it counting my object in the projects part as part of the scene
I have code here that says if it is null then do something but its counting as the one as a prefab
You need to provide the error and the relevant code.
For basic player movement in a roguelike / top down game, should I use transform.Translate or rigidbody2d.movePosition
Hey :=) I want to trigger a Coroutine when a gameobject has moved past the cords "x = -5"
My idea was;
void Update()
{
if(transform.position == new Vector3(transform.position.x, -5))
{
StartCoroutine(KnightAttacking());
}
}```
But that just does nothing :( Any idea?
@subtle zodiac nope
:):)
So the project i'm working on, I want to make it a 2d game with sprites that have paperdolling for equipment. But I can't find any useful tutorials on how to set this up with the animator stuff, does anyone nave any videos they can recommend or anywhere to point me in a direction of getting 2d stuff set up for having something like this without it being an absolute nightmare?
I'm starting to think it might be easier to just do it all in code instead of trying to use the animator tools
hello anyone who might be able to help, I would like to put in a particle system to the main menu in my 2D game, however when i make the system it doesn't show over the background, I've tried moving it to the top of the hierarchy but still not showing, Any solutions?? Thanks again
Hey does addforce() work in 2d?
@left nest yes work
awesome thank you :D
ok np
@left nest rigidbody 2d is specific
ok
not add force
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
{
@wide canyon what do you need?
A shooting delay
@wide canyon put it in IEnumerator
and a yield
What's a "IEnumerator"?
but checking input will disturb i think π€
hmm
Here is the documentation
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
lol @left nest
lol
i think that input will disturb @left nest in checking ienumerator
and if he try in update it will do instantly
mine is clear. Input.GetKeyDown()
player will automatically slow lol
hmm
maybe have the Ienumerator just has the slow down and the input starts the ienumerator
but input in ienumerator.... I don't think
and starting from Update will run instantly
no wait in ienumerator
this sucks
input?
that's what i thought
@wide canyon input sucks?
anyway i am telling you one more thing. just wait @wide canyon
use this kind of code https://hatebin.com/mgiywoslvb
but don't just copy
use your mind also
I'll check it out @rocky vault
nah, unity coding.
ohk
It's hard as hell finding what you need
@rocky vault If I need help with some other stuff can I dm you for help?
ok you can @wide canyon
thanks bru
np @wide canyon
anyone know a way to make scrollbar adaptive from size of TMP?
@dusty nebula do you use the scrollrect for this?
I am currently testing a 2D platformer with pixel precise art.
The black lines at the top and the bottom of the ground tiles should have the same pixel width. But when I play, the length of these lines do not stay equal. Sometimes the one at top is a bit longer, and sometimes the one at the bottom. What could be the cause of this problem and how could it be fixed?
yes
but when i edit the scroll not expand
and i have other problem
this is a camera bug or tileset is not correctly sized?
and on buid i have this line
in unity editor not have
try to give your tiles a border of 1px for example. And it should expand when you set either a layout group or a content size fitter to it
When I use the Atlas Sprite the textures are weird, is it a bug? (Yes is minecraft texture)
texture size 16x16 px
can someone help me ?
"I cant reach pink color so hard"
it works like it should but its saying the thing in the prefabs area is part of the game
the gold circle is the prefab btw if that helps
any way to enable a tilemap through code like this?
.setactive isn't a thing on tilemaps and it's bugging me
scale 1 1 1?
hahaha I made it!
I placed the tilemap in a GameObject and put a active/inactive bool on it :D
tricked my way around the entire thing, meh, as long as it works?
Tilemap is a component
you can Tilemap.enabled = false
setactive is only for gameobject
okay, that clears up a lot, thanks!
im having some issues with console errors whenever i create a new 2d project. Would really appreciate some help getting this resolved if anyone can help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class TerrainGen : MonoBehaviour
{
public Tile grass;
public Tilemap tilemap;
// Start is called before the first frame update
void Start()
{
basicGen(0, 0, 50, 3);
}
// Update is called once per frame
void Update()
{
}
public float scaler = 1.5f;
void basicGen(int X, int Y, int width, int height)
{
for(int x = X; x < width + X; x++)
{
for(int y = Y; y < height + Y; y++)
{
int grassHeight = Mathf.RoundToInt(Mathf.PerlinNoise((float)x * scaler, (float)y * scaler));
tilemap.SetTile(new Vector3Int(x, grassHeight, 0), grass);
}
}
}
}
i have a script to generate rolling hills with perlin on a tilemap, but it only produces very limited results
higher
Then multiply the output of the perlin noise
kk thx
hrmm
Interpreting that as a "it's going well" π
lol
hey im going through some tutorial for making a 2d game and im attempting to use Debug.log to print something in the console and getting an error
this tutorial isn't telling me to define anything beforehand
capitalize the L
if you dont have intellisense check pinned in #π»βcode-beginner so you dont run into these sorts of problems
Fixed it using the Pixel Perfect Camera
how can I transform a 2d mesh into 3d (extend it along the z axis)?
@still tendon
in whatever code you use for the actual jumping
check to see if the player is crouching firs
if the player is crouching, don't jump
This is why I use enums and switch statement
enum State{
IDLE,WAlk,JUMP
}
State state;
//... later on
switch(state){
case State.IDLE: break;
case State.WALK: break;
}
With your current design, the easiest thing would be:
void Update()
{
crouch = Input.GetButton("Crouch");
jump = Input.GetButtonDown("Jump") && !crouch;
}
Hello, I'd like to rotate this bow to 0, but due to some Quaternion stuff I really don't get the bow does a flip if the character is turned to the left, despite only being turned locally. Anyone got an idea on how to fix?```
CODE:
//Coroutine gets called 2 seconds after shooting
IEnumerator RotateWeapon()
{
// Loops until rotation.z == 0
while (PLR_WeaponTransform.localRotation != Quaternion.identity)
{
// Lerps rotation
PLR_WeaponTransform.localRotation = Quaternion.Slerp
(
PLR_WeaponTransform.localRotation,
Quaternion.identity,
6f * Time.deltaTime
);
yield return null;
}
}
@celest island Try using localEulerAngles instead of localRotation. It's a vector3 and it doesn't have as many weird maths
Now that I've experimented it actually works if I store and do all the rotation calculation in a handy Vector3 and just convert the vector to a Quaternion when I have to update the rotation. Thanks :3
Hey all, is it just me or when i try to change a rigidbody2dβs body type from script it drops all colliders attached to it?
how do i get the camera to follow my character?
nevermind
how can i get the speed of an object as a float?
You could initialize the speed variable as a float or typecast it in an expression (to float) if it was of another data type. Hope this helps π
Hi guys, I'm making a mobile game and can't figure out resolutions, how do you make it so your game looks the same on all screen sizes? Thank you very much in advance!
Hey peeps, can someone help me create a level where the walls and floor close in on the player?
@still tendon Click on an object, hover over scene and press f
to re-align the camera
thanks
that is the question, isn't it ? :) .. unfortunately there is no simple solution .. you could set Canvas to camera space and enable auto scaling .. it will automatically scale all your UI elements to fit any resolution .. but aspect ration is another can of worms and there is no simple way out (or at least I'm not aware of one) .. you'll have to make UI in a way that it adapts to different aspect ratios or design it in a way that it would fit your targeted platform
Alright, thanks!
unity canvas scale with screen size + proper use of anchors
anyone having trouble with shadowcaster2d and gc? each of my shadowcaster create a 1.9kb gc alloc for some reason (coming from ShadowCaster2D.Update())
im not sure if im doing something wrong or what, also i have to setup code next to each shadowcaster wit ha OnBecameVisible and invisible that set on and off the castShadows cause if i just disable the component or game object the number of batch get added everytime
also adding global volume bloom seem to add 19 batching at any cost... anyway to drop that down?
How do i animate a Sprite Sheet 2D in a particle system ?
create a mat for your sprite set it in the renderer of the system then check the texture sheet animation and write the number of row and column your picture have, then you can setup the speed it plays and all, make sure its on the good layer if you are using layers (set it in the renderer)
yeeaah about that when i assign the sprite to a mat it distorts
like UUhh
its just cause the preview is set to sphere
or not
dunnoh lol as long as it work when animating
show your particle system screen shot
@atomic patrol
all you need is that mat set in the render and setup the texture sheet like this
number of cycle is the number of time its animation during the duration of the particle
me i had 3 image on same row so x is 3 y is 1
hey guys, can you give me any pointers on how to achieve this kind of collision when using 2d tilemap, basically I want player to be able to step in the tile from one direction, but also be able to move behind and from NE and NW side
Have someone a tutorial or has the script for a level generation?
@north oriole Not sure what type of level generation you're looking for, but here's a youtube search of procedural level generation tutorials
https://www.youtube.com/results?search_query=unity+procedural+level+generation+tutorial
why particles do not show when i play like Uh
@ocean wing thanks but i want link to have prefabs and end positions and i need a scipt that place a prefab at the end a prefab
@north oriole Almost like placing blocks?
I have predefined level parts and a different one should be spawned after each level part @ocean wing
like here
but i dont now how i do it
@north oriole if you know the position where each part should go then use a for loop to go through all the parts in the list and instantiate for each position
i need help on placing and taking object ingame on a grid
like taking a chair and move it to another part of the house
very basic but i dont find anything, can someone give me direction on what keyword to use
closest one i find used in farming-like game, where the object doesnt actually "moving" but farm tile contain all the plant sprite. thats one method for sure but then i would have to fill the whole house floor with gameobject and store all possible furniture sprite in every single one, including orientation of multiple-tile furniture
surely theres a better way no ?, or it realy isnt as simple as i think it is ?
anyway my goal is to make 8x5 tile house with simple gameplay of decorating the house, any help on how i should approach this would be appriciated
ok so this is a tip that i discovered the hard way: apparently colliders on children automatically connect to the parent's rigidbody, and adding another rigidbody to the child leads to sorta unpredictable results
@neat hollow to detect an object use ray-cast of tjat ray hits the object you make it follow the player position or mouse depending on you and when click the right mouse button you place it
huh
why would someone even add a rigidbody to a child anyways
Mistakes happen




.