#๐ผ๏ธโ2d-tools
1 messages ยท Page 61 of 1
Are you doing so in a physics-friendly way?
I suspect not
if you're modifying transform.position that will completely ignore the physics engine
or using transform.Translate
1 sec
transform.position
but i will need to rewrite the code?
or i can use physics with transform.position
You could use rigidbody velocity to move your character. Transform.Position basically ignores everything else with the only mission to move the exact amount that you told it to, so if zed amount was large enough it would run right through the colliders
you will need to rewrite the code if you're using transform.position
of
hmm
is there a way of verifying unity
idk why my unity just crashed and it isn't starting
man it's late here and my unity just broke
i will try tomorrow
im very sory
if (enemySpawnerTilemap.GetTile(x, y) != null) anyone know why GetTile hates this?
"No overload method for GetTile takes 2 arguments" but anything i try to throw in for the z doesnt work
it takes a Vector3Int
already tried that
it doesnt work
it just zooms off into infinity
Nvm i got it working
it was moving the camera beyond the scene
from z = -10 to z = 0
solved it by using a vector 3 with a fixed Z
could anyone help me out with a bullet script right now i shoots the wrong way and i think it has to do with this line of code
transform.position -= new Vector3(Mathf.Sign(Player.transform.position.x - transform.position.x) * Velocity, 0f, 0f);
no matter what i tried i either keeps shooting the wrong way or it stays on the player every frame
https://gyazo.com/cebed3bced3da20f95ad9813b91878ca
Just inverse it
Use the profiler to see where the bottlenecks are.
acctualy
the game was running at 20 fps
so
i set the targeted framerate to 60
works fine
- adaptive performace
how can i reduce the loding time to load a scene
reduce the objects in your scene, learn to load things only when needed, dont put prefabs in the inspector, rather try to use addressables. a lot of approaches there
ok
but
i resolve that problem by doing some weird shit
but my splash screen is not showing, but unity's is showing
why
instead of my splash image
there is a black screeeb
Please try to not spam the chat with one word posts... you did say loading time. So is your scene showing or not? If there is no scene showing, you maybe did not set any to be build in the scene overview.
my splash screen image not showing, just black image, after a few seconds, the unity's splash screen pops up, and after the game loads
Okay, so where and how did you setup your splashscreen? @undone gorge
player settings<splash screen
yes
You gotta add it to the logos list
load them on demand
instead of all up front
how
how can i do that ?
hi
my animator does a strange thing
when going fromany state
to some animation
the play_hide bar is not moving
it just stays there like so
it starts
it changes the sprite to hiding
but doesnt play the animation
ok fixed it
i need to check trigger not bool
Hello
I'm currently doing a 2D platformer game and I need one last step to finish it off. When my enemy goes below a certain Y co-ordinate I need it to trigger my EndGame scene (I already have the code for)
I think my method is wrong but I dont know what to use
(Using c#)
I don't know how to do either, I'm fairly new
a timer is a float you add time.deltaTime
with an if statement checking if it bigger than the desired value
I've heard of it but I can't say I know how to incorporate it too well
well depends on what you want
Is there no way I could use time delta
yes
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float moveSpeed = 5;
private bool walking;
private Rigidbody2D rb;
private Animator anim;
private Vector2 movement;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if (movement.x != 0 || movement.y != 0)
{
if (!walking)
{
walking = true;
anim.SetBool("walking", true);
}
Move();
}
else
{
if (walking)
{
walking = false;
anim.SetBool("walking", false);
}
}
}
private void Move()
{
anim.SetFloat("X", movement.x);
anim.SetFloat("Y", movement.y);
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}
I cant get my 2d character to move with arrow keys could someone help me fix the script?
MissingComponentException: There is no 'Animator' attached to the "Front" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "Front". Or your script needs to check if the component is attached before using it.
UnityEngine.Animator.SetFloat (System.String name, System.Single value) (at <753965d1225041ae90af37ef632f784e>:0)
CharacterMovement.Move () (at Assets/Animations/CharacterMovement.cs:52)
CharacterMovement.Update () (at Assets/Animations/CharacterMovement.cs:36)
As the error says:
You probably need to add a Animator to the game object "Front". Or your script needs to check if the component is attached before using it.
Also, large codeblocks should be posted via paste sites as mentioned in #854851968446365696
I added the animator but it only moved the scene screen not the actual character
nvm got it to work
Assets\Scripts\Player\PlayerMovement.cs(18,28): error CS0117: 'Input' does not contain a definition for 'getAxisRaw'
need help again
np
If you're making capitalisation errors, do you not have autocomplete? If not, configure your IDE using the instructions in #854851968446365696
so ive been trying to figure this out and my dash only works when i press space and left shift at the same time, how do i fix this? ```csharp
void Update()
{
horizontalMove = Input.GetAxis("Horizontal");
transform.Translate(Vector2.right * speed * Time.deltaTime * horizontalMove);
if (Input.GetKeyDown(KeyCode.Space) && playerJumps < maxPlayerJumps && isGrounded)
{
playerJumps++;
if (playerJumps == maxPlayerJumps)
{
isGrounded = false;
}
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
Dash();
}
}
void Dash()
{
if (Input.GetKey(KeyCode.LeftShift))
{
rb.AddForce(Vector2.right * dashForce, ForceMode2D.Impulse);
}
} ```
That's what your logic is saying
If you want it to only work when you are holding shift, then move Dash(); out of the enclosing if statement
oh im dumb i didnt see that
I am trying to make directional particle system works in 2d space. The particle will instantiate on point A to point B, i cant really get my head around the rotation in the Particle System.
I have a problem with the jump animation in my character. Where should I add the IsJumping bool of animator in my script.
This is my character controller script
https://paste.ofcode.org/fVELPYkeuyBcc7MPwgMfPv
well.. shouldnt you add it where you jump?
i'm assuming here, since it's commented as "JUMP"
there is a double jump code So, idk where to add the code
I dont think it'll make a difference? I'm assuming you want the jump animation to play when you jump. double jump or not
so look at your own code, and see where your jump logic is, then add that there
Can i add two True bools?
sure..? if you have different jump animations, I guess so
i am using same animation.
well ask yourself why you think you need two bools first then
Your question is.. bizarre. Did you copy paste this code from somewhere?
no
So then why can't you pinpoint where the jump logic is?
ok i'll try
I believe I found it here anyway, so why can't you set the isJumping bool of your animator there?
ok thanks for your help
I'm currently making a ship building part for my game; I want to have a screen that pops up where you can see / edit the blueprint for your ship before going back to the real ship and building it. Should I / can I implement the blueprint mechanic in a second scene that is overlaid over the first scene?
not sure if that was clear
Yes, you can have multiple scenes stacked.
Howdy folks. I'm trying to rip a sprite sheet on runtime and dynamically store them as sprites to use in the assets. Can someone tell me why what I'm doing is wrong?
Sprite icon = Sprite.Create(spriteSheet, new Rect(50, 3, 7, 7), centeredPivot);
AssetDatabase.AddObjectToAsset(icon, icon.texture);
I don't totally understand how sprites are stored, trying to add it to the texture here, which doesn't seem to yield any results beyond this:
I might just try to manage without doing this
Just wanted to know if there's actually a way of storing the created sprites
It looks like your image is stored in the assets folder somewhere?
If you're loading a sprite at runtime it would prresumably come from outside the project folder(s)
and if you want to save it you'd save it in Application.persistentDataPath
However:
AssetDatabase``` is not something you will be able to use at runtime
that's an editor-only thing
Gotcha, welp! I think at this stage I've decided that saving the sprites in that manner isn't really necessary; what I'm trying to do is basically dynamically create an animation set from a sprite sheet
I've run into an entirely different issue with that though
I have no clue at all how you're supposed to set a keyframe value using a sprite.
Because a Keyframe can only take two float values
One for time, and one for the actual value of the frame

No clue how Unity is pulling off the witchcraft that is just slapping some sprites into an animation
This ain't no float
Say the dark blue walls (tile map) and white grid (quad) were supposed to be inside the frame (the light blue box) how would I make it so that anything outside of the box didn't render?
Is masks what I need to look up?
Just noting for anyone who might care; turns out what I need is an ObjectReferenceKeyframe, which is totally undocumented.
interesting I was looking at the API and was at a loss
Is there a way to check if a collision ends im trying to make a platform that destroys after a little bit of time but i want it to only destroy if the player is on the platform so i need to know if the player isnt on the platform anymore.
You can use OnCollisionExit or OnTriggerExit depends of how you setup your Colliders.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionExit.html
Hello Comunity, i want to ask about loop,how to call method every X time? with systematic
private void MyMethod(){
//Do our stuff here.
StartCoroutine(RepeatMethod(1));
}
IEnumerator RepeatMethod(float seconds){
yield return new WaitForSeconds(seconds);
MyMethod();
}
@fleet knot This should repeat MyMethod every 1 second
Thanks ill try this
Hey guys, I have a big problem that I've tried fixing for 3 days, basically my game has a tilemap (2d platformer) and the tilemap uses a polygon collider. I have some dropdown platform that use the PlatformEffector from unity. The two colliders (tilemap and platform) are perfectly alligned at the top, but everytime my player walks from the tilemap to the platform. He glitches. I looked online for solution to maybe merge the colliders but I cannot since one of them uses the effector. Does anybody have a clue on why it's doing this?
i need a 2d unity to dm me
Itโs program, it may have some trouble formulating words
probably a quick video would be helpful so people can see what "glitch" you're talking about
Hi
I would need to know if it is possible to do something like this
the two green lines being connected to the two black circles
and when I move one of the circles
the green lines to move like this
without changing size
(I want to use it for hands)
Yeah, sebastian lague just posted a video the other day on that actually
@mossy fossil https://youtu.be/PGk0rnyTa1U?t=180
Anything on applying masks to quads or mesh renderers?
Guys I have a question
It's not about coding
I'm making a 2d space shooter game
And I'm trying to add a wall so that my spaceship cant pass through
I tried to add the 2D collider, but it didnt block
What should I do?
your spaceship needs to have its own collider and a Rigidbody, and you need to move it in a physics-friendly way
I have BoxCollider2D attached on this wall
e.g. no transform.position = or transform.Translate
And have the wall rigidbody static
I have the Rigidbody2D attached to the player, with body type = dynamic
you have to move the ship via the Rigidbody2D
right you have to also move the ship with the Rigidbody though
what do you mean?
i mean
what I said
move the ship with the Rigidbody methods
not via the Transform
in your code
Alright
Let me try
So basically
I ahve to get the rigidbody2D in the Start
Then in the code which I use to move the spaceship
So right now my code for moving is like this:
float Inputhorizontal = Input.GetAxis("Horizontal");
float Inputvertical = Input.GetAxis("Vertical");
transform.Translate(new Vector3(Inputhorizontal, Inputvertical, 0) * _speed * Time.deltaTime)
yep - Translate is no bueno
it ignores physics
You have to either set rb.velocity
or use rb.MovePosition
in FixedUpdate()
or rb.AddForce
Ok
I know the AddForce one
Thank you!
Ok if I dont use the Rigidbody2D
But I want to write in the coding
that the spaceship can't pass through a certain X
As if there's a wall there
How can I do it?
So it's like I have the wall with collider, and if my spaceship's OnTriggerEnter2D hits the wall's collider
What kind of code do I write so that the spaceship remains there even if I press the left arrow
you'd have to do your own custom raycasting, find where the wall is, know your ship's physical extents, and only move your ship up to where the edge of the ship would touch teh wall and no further
the code is a bit more complicated
not that complicated though
I'm trying to add a bool
And make the MoveLeft and MoveRight 2 different voids
So when the spaceship hits the wall, the bool _stopMovingLeft is true, and the spaceship can move towards right side
Can I not make a simple tile asset? or does it have to be rule tile?
try something like ```cs
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out hitRight, 1f))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.right) * 1, Color.green);
if (hitRight.collider.tag == "Wall")
{
canTurnRight = false;
}```
so in your update move you simple do cs if (Input.GetKey(KeyCode.D) && canTurnRight) or something
Okay I added the rigidbody and found a script to move my spaceship with rigidbody
float Inputhorizontal = Input.GetAxis("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(Inputhorizontal * _speed, 0.0f);
But why my spaceship still passes through the wall....
I even tried to Debug.Log if the collision has been detected
i already pointed you the way with a simple raycast to detect wall
raycasting is fundamental
I know
you can also limit the transforms axis by certain range
How do you do that?
yo i havent used unity in a while so i sorta forgot this but how do i change the time the animation starts and its speed within the unity animator
transitions?
click on the arrow transitioning one clip to another
speed is in the clip itself or you can use multiplier variable
it startts at the wrong frame
so theres no step
second for sprinting i need to up the framerate
so how do i fix those two probs
screenshot your transition from idle to run or w/e
alr
thats the main anim
idle > playerrun
you tried moving the bottom clip closer?
it works sorta but then when i stop running it dosent smooth back into idle
try fixing your exit transition now
generally this what a blend tree is useful for
you can drag those bars, or open up settings to adjust numbers
the tab settings you can decrease more of the transition time yes but also moving bottom clip closer helps
also this is better suited in #๐โanimation tho
oh yeah srry
wait the animation thing isnt looped right
like that entire thing is just one time
cuz ive been moving it closer very slightly lmao
there is a preview window if that's what you want
nah i think i got it
theres like very small movement bugs but i dont have enough ocd to need to fix that rn
overall its fine now
its better though?
yeah
ok yeah, if you want smoother look into learning blend trees
alr
ill prob do that when i decide to fix the mini movement bugs
is there a way to check on OnTriggerEnter2D if the object isnt colliding with anything? i want the same button press to have a different action depending on the object colliding or not
oh i forgot about that thanks
overlapXXX
I still cant code movement ive tried using tutorials such as brackeys but it hasnt worked would anyone has like a movement test file i could use
how come you're unable to get things working if you're following tutorials that tell you exactly what to do? what goes wrong?
i dont know what wrong
ive been working on this for the past week as a hobby
i feel like i am going insane like its a big joke i cant stop laughing
#๐ปโcode-beginner message
Learn the fundamentals first instead of copying blindly
that wont work for me
and why is that?
i have a hard time following videos
i prefer to have a class where i can ask questions
well then.. go to school and pay money
or you know, actually go through that and ask questions here?
you'd know that if you went through the C# tutorial like I said, and not just glanced at how "oh, there's a video up top", it's not videos
it's interactive exercises where you read, and try out coding yourself
okay
Hello, I am using Physics2D.CircleCast to check for collisions. It seems that it first checks from the right side of the object, then traces around the circle clockwise, causing first point of contact to be the right side in cramped spaces
How can I tell unity to start the collision check from another point (such as the bottom of the circle?
how do i play a sound on a collisiion trigger in 2D?
break it down and try searching
1)how do i detect a 2d collision
2)how do I play sound
รถk
how do i wait til an animation has finished playing?
thank you loki
The character moves automatically and I can't control where it does, I suspect it's prolly in this part of the script:
private void FixedUpdate() {
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
Vector3 moveDelta = new Vector3(1f, 1f, 0f);
transform.localScale = new Vector3(-Mathf.Sign(x), 1f, 1f);
transform.Translate(moveDelta * Time.deltaTime);
}```
your move delta is always at 1, 1, 0. You should probably be using your x and y variables in your moveDelta vector
also there is a good chance you probably don't want to be using transform.Translate for movement, unless you don't care about physics/collisions working correctly (or you are planning to implement your own collision detection)
are there any up to date tutorials for 2D? It seems like a lot of the tutorials I'm finding were made before Unity included more 2D functionality to the engine.
They mostly still work fine. Is there something you're trying to do you can't figure out?
Off the top of my head, most of the 2d improvements were in rigged 2d animation, tilemaps, and the spriteshape tool. Physics and other basic functionality hasn't really changed.
I need helo with AI patroling
help*
it doesn't have errors but it has a seizure every time it plays
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.
thats the code
@subtle vessel I played around with unity about 6 years ago when 2D stuff wasn't that good. had to use an asset packaged called TK2D to do stuff like loading sprite sheets, animation, camera, etc.
now it looks like a lot of that functionality is built into Unity, but a lot of tutorials I'm finding don't show how to use that and instead rely on an outdated library to do 2D stuff or they use their own system
I am trying to create a game that uses the right click button to hold and rotate the camera around an object in 2d.
My main issue is about having the camera not instantly switching around because of relative x positions.
Here is my current code:
//Camera Controls
if (Input.GetMouseButtonDown(1) == true) //As soon as the mouse button is clicked.
{
pMousex = Camera.main.ScreenToWorldPoint(Input.mousePosition)[0];
} else if (Input.GetMouseButton(1) == true) //The frame after. (when it is being held down)
{
mousex = Camera.main.ScreenToWorldPoint(Input.mousePosition)[0];
player.transform.rotation = Quaternion.Euler(0, 0, cameraSensitivity*0.1f*(mousex - pMousex));
} else if (Input.GetMouseButtonUp(1) == true) //As soon as the user lets go of the button.
{
}
I'm not currently sure as to what I should do so it starts off rotating from it's last set position
The second if will never run. That's not how frames work.
Each call to Update() is a new frame. A single pass through Update() is always the same frame.
Within that call, "Input.GetMouseButton(1) == true" will always have the same value
If it is true, then the first "if" clause runs, the later ones won't because that's how if/else works
the second if will run on the second frame of the mouse being held. The first if is GetMouseButtonDown()
oh holy heck, I misread that badly
how do i make an animation play when i am attatched to a wall? it keeps getting l stuck after i jump off of the wall instead of when i am on it
i have a transition from run anim to the wall anim which has conditions set as run = false and wall = true
i also have a transition from the jump anim which is wall = true
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.
i'm trying to make a random generated towerd defense game i followed a tutorial on this code and everytime i started the game it displayed an argument out of range massage, how do i fix it?
Double clicking the error takes you to which line?
it didnt take me to any line
Show the complete error in detail.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <eae584ce26bc40229c1b1aa476bfa589>:0)
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
MapGenerator.getBottomEdgeTiles () (at Assets/Script/MapGenerator.cs:38)
MapGenerator.generateMap () (at Assets/Script/MapGenerator.cs:59)
MapGenerator.Start () (at Assets/Script/MapGenerator.cs:17)
Map Generator line 38
Which line is line 38?
Perhaps you meant i < mapWidth
it does, thx
i got an error saying The referenced script (Unknown) on this Behaviour is missing. does anyone know how to fix
Check your console for errors.
Show your console
show ss
Your entire console.
Jeez, as in, the entire window. What's with these partial screenshots, damn. The point is, to check if you've hidden compiler errors.
There's three buttons at the top right of the console. Is the first one disabled?
Try removing the component and adding the script you want.
damn plagiarizing is hard
welp time to do what i came here to do
I added a dash script from YT and its not working
How do i fix game object destroying it self even though there is no destroy function in the script?
something is causing it to destroy itself. check why
have you saved your script
i cant find the source of the problem
if you control shift F, and type destroy, does anything come up
nothing come up
i've tried
when does it destroy itself
every time it starts
when you press play? do you have a lot of scripts?
no, one really long script
put that really long script into a paste site and share it here #854851968446365696 has links to paste sites
wdym
have you ctrl+s? it needs to be saved before the code gets compiled. I see a dirty marker on the top, that's why I asked
yeah
then you're going to need to be more specific on what doesnt work. are there also any errors?
nope
there is nothing wrong except that i added a shift dash code and it does not work at all
and i have no idea why
have you attached the script to an object?
use Debug.Logs to check which of the conditions it's not fulfilling in the if statement
the empty void should be filled with tile that has different color
yes i did
is there something wrong with the script?
Path color looks like alpha is 0. it's there, but transparent maybe? You should click where the path is and actually see if there's an object there. Also check your own hierarchy
i dont know. I'm not bothered to look through someone else's script that you copied anyway. If you copied it and it doesn't work, usually just means you didnt copy the process properly
learn to debug it
use debug.logs. print values. check.
your right its transparent, but how do i make it not transparent
i don't think i copied it wrong since i checked it 3 times out of boredom
click on it in the inspector, and change the alpha there
whats an alpha? sorry i'm new to unity
color is made up of 4 channels. r g b a. a is alpha. it's the transparency level of the color
ok thx
do anyone know a good asset/tool for 2D movement or character controller? , cuz most of them are more related to 3D
it works
Anyone help me with the Dash script that i added it doesn't really work or give any errors
i have no idea what im looking for tho
check if IsGrounded is false. check if movX is not 0
does not exist in the current context
you should learn some basics
<#๐ปโcode-beginner message>
.
I'm having trouble adding a rigidbody2d. I added it in my script, no errors. However, when press the play button (to add the rigidbody2d), it adds it perfectly fine but skips ahead.
what do you mean by skips ahead
It adds the rigidbody2d and like 3 seconds later, gravity takes over and it goes falling
any clues?
how many go obj u have?
I don't think it's because of the amount, if I have just one it does the same.
if im making 2d animations in aseprite for unity, would i need to make all new files for each animation, jump, run, walk? or do i do it on new layers
when i buy sprite sheets from the Unity store they are in 32x32 frames each frame of animation in its own image file @fast gyro
ok thanks
even if they were all on the same image you would still have to slice the image file
hey mate, your questions about art and stuff would be better off in #archived-art-asset-showcase or #๐โanimation . However, there is no reason you would have to limit your pixel art to 32x32, you can use whatever size(s) you prefer
ok thanks man
i don't know thats just what the pixel artist does when i buy them
Hello, I'm trying to toggle the SpriteRenderer component of an array of 2D objects with a given tag. How can I change them collectively rather than connecting each individual renderer? An image of my script is attached
heya, is there any way to change the alpha of a whole tilemap without going tile by tile with a foreach loop?
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap-color.html alpha can be set with this
Simple question probably (I'm a beginner), but how would you get a character to collide with the border of the camera? Want to have something to prevent them from moving offscreen
you can either put collider boxes on the edge of the screen, or detect the position of characters and stop them from moving when they exceed a certain position
Better way of doing the second method is to use some form of ViewportToWorldPoint or WorldToViewportPoint thing, where viewport is the coordinate of your camera's view
starts from 0,0 at bottom left. 1,1 at top right
The first method seems to work good enough, thanks!
Simplest solution seems to work the best for what I need for now.
Hi, I want to make a "rubber-band" like physics in my project, where a link will be connected to a fixed point, and an object at the end of the link. The link can be stretch or shrink based on the distance between the fixed point and the object. How can i do this
https://docs.unity3d.com/Manual/class-SpringJoint.html maybe this is what you want
the problem with this is that it will push back the object when it is getting near the fixed point, which I dont want it to happen, unless I should modify its spring frequency based on their distance ?
because when you put the Frequency too low, it has very little effect to control over their maximum distance too
the frequency?
ahh, I found what I wanted, which is DistanceJoint, but it does not have the elastic properties like SpringJoint, maybe I can combine them?
the frequency determine the number of times it check for both objects to stay at a certain distance
Guys, I am trying to make a function that lets me know if a tile at a certain position is in an island or it is connected to land.
This image is an example (it is procedurally generated). If a sand tile within the red circle is taken, it should say it is part of an island, the other tiles instead are part of land.
Wheel joint may be worth a try
It has more options
alright, i finally got it to work. my code was faulty and i just thought it was impossible to do what i was trying to do
but now ive come across a whole new problem
I'm using rule tiles in my project, and now that i have tiles that disappear when you touch them, id want them to blend in with the normal foreground
but i have no clue how to do that
do you keep your tileset inside the same folder as your tile palettes?
i do
i'm trying to design a project layout
i'd look to peek at how the professionals do it
You mean assets folders etc or something else?
If you mean folders, we donโt have a special way to do it and itโs hit or miss on professional projects xD
i'm talking about the folder layout for assets yeah
a tiny desktop makes for an easy project
i'm trying to organize everything so whenever i want to update the game in the future its really simple
at the moment i'm working on folder layouts for tile palettes and a naming system
i've been coding thinking that anim.GetCurrentAnimatorStateInfo(0).IsName would return a false output once it finished playing the animation haha oof
while not looping
Example 1: condition when a animation finishes in unity if(anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 1){ //If normalizedTime is 0 to 1 means animation is
you live and learn
Hello! I am looking to create a way switch a bunch of tiles with other tiles via code.
My end goal is to make a sort of season effect. Eg. at one point tiles are grass, and another time snowy.
What would be the best approach to this problem?
Iโve seen that, but I donโt know if this would be the best solution. As it would require a bunch of if statements for each type of tile?
Actually, I think this may work if I have both the snowy and grass tiles with the near identical names (maybe like โgrass0โ and โsnow0โ). So then I will be able to get the name of the tile and replace it with the other tile
Any reason why a jitter between two gameobjects on collision would randomly start occurring? Everything was smooth until now.
Well, I went in a changed my camera to fixed update and it fixed not sure why after 100s of hours of developement this issue just started
doesn't the pixel perfect camera stop jittering movements?
It is conceivable that you have reached a level of complexity, which requires a bit more thoughtful planning ahead.
- The correct order of logic between void Update, FixedUpdate and LateUpdate
- Script execution order
is it possible to do this "if (anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 1)" but for a specific animation not just whatever animation is currently playing?
I work in AAA and pretty much all of our code is dumped into one folder, sooo... I wouldn't say "professionals" have any standard xD
I'd say this is pretty clean
What is your experience in making anything with Unity?
Then start with learning how to use Unity before you jump. There are tutorials in #๐ปโunity-talk.
If i have a sprite with multiple colliders on it how can i detect which collider collided with something?
Collision2D contains that information. See the poorly named "otherCollider" property:
https://docs.unity3d.com/ScriptReference/Collision2D.html
Hope a small picture is alright. I'm looking to create a similar 2D map for a project, ideally something I can position sprites around and handle mouse interactions. Anyone have any suggestions on how to approach this?
Trying to avoid the Tilemap if I can, it's a bit much and doesn't provide the seperator lines between the tiles at runtime anyway.
i'd personally use the tilemap and have the sprites have a faint white outline so that it looks like the grid, but if you really don't want a tilemap then i'd do an executeineditor script that has a field for the size of the grid, the size of each tile and a prefab for the default tile then do something like
[pseudo code]
for(i = width)
{
for(j = height)
{
Vector3 position = new Vector3(i * tileSize, j*tileSize);
Instantiate(tilePrefab, position);
}
}
for this to work u'd have to have the size of tilePrefab the same as tileSize, and only have this script run once so disable the script after the firs time it runs so that u don't have lots of tiles
then u could manually change out the sprites for whatever tile u want
and it would be neater to have all tile objects under one parent so assign that when the tile is instantiated
For detect and interacting with items in 2D, which way is more preferable?
A) Raycast
B) An Invisible TriggerCollider as detection
What are the pros and cons of using this 2 methods?
help whenever my 2d character is supposed to run infinitely but keeps on stopping on the way like there is sth invisible blocking
Its being animated and root motion is turned off and i have frozen the z rotation on the rigidbody.
is there a way to check if a specific animation is playing not just if an animation is playing?
check that there are no colliders there that you can't see
oh ok awesome
Hey, so, when I create a sprite using Sprite.Create(...), how might I go about saving that to the assets in-editor?
Is it possible with AssetDatabase.CreateAsset?
As far as I'm aware, you need a file extension for that, right?
Can you just use .asset?
Actually, it seems like "yes" is the answer
Alright, so I've encountered an odd bug
Basically, I've created a script that will rip a texture into separate sprites, then save the sprites, then compile the sprites into animations, and finally an animation controller
For some reason, though, the resulting animations have some weird behavior
Particularly, each generated animation will only play the first frame, unless you do this:
I assume this refreshes the animation or something and establishes that these frames actually exist
But you can't just do this once
This happens every the game is played
Just locks up on the first frame until you move the keyframes back to where they actually go

Dunno
The problem also doesn't get fixed by restarting Unity
Somehow something just isn't interpreting the presence of the keyframes until I manually set them
The animation preview in editor also gets locked up on the first frame until I do the above, but in play mode, it needs to be done again
So I can't even just replace the frames in the editor and be done with it

Has anyone done 2D Topdown lighting?
I guess that of similar of say, ALTTP. But rather then the shadows being baked into the sprites themselves, they're dynamic?
Thought about that. I also know Unity has 2D lighting as well now.
it does have post processing
Is there a simple way to make the camera be the perfect size to fit for example 10 tiles by 10 tiles without cutting halfway through a tile at the side
if you're using an orthographic camera you can use Camera.orthographicSize to set the height of the camera
and then the width is based on your resolution aspect ratio
Yea i cant find a balance idk if im being dumb
so if you want to set the width properly you'll need to do a little math with the aspect ratio
a ill try tomorrow again ig its been a couple days out of frustration lol
the math is fairly straightforward:
aspect ratio: AR
height: H
width: W
AR = H / W
W * AR = H
W = H / AR
also
H = AR * W
So if you want the width to be 10, then you do:
H = AR * 10
aka just multiply the aspect ratio by 10 and that's the orthographic size to set to the camera
width and height are in tiles as its unit right
ah okay
How would I apply a prefab to a tile that isn't a rule tile? particularly during run time
Or would I just make a rule tile?
anyone know why this wont decrease the enemys health? ```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float health;
private Bullet bulletScript;
void Start()
{
bulletScript = FindObjectOfType<Bullet>();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Bullet")
{
TakeDamage();
}
}
void TakeDamage()
{
health -= bulletScript.damageAmount;
if (health <= 0)
{
gameObject.SetActive(false);
}
}
} ```
Add some logs or use the debugger to see what's being called
you have to call takedamage on the enemy
vertx you gotta try a little man
They do.
I did.
on the enemy?
yes
yea
Also, the logic for getting the bullet seems flawed. This would only work if there was only one bullet. You should be getting the bullet component from other.gameObject
is damageamount a property?
?
you might need to do damageamount()
Or, you should inverse all this logic as Master Bronze Elite implicitly suggests, and have the bullet handle dealing damage to the things it hits (via an interface perhaps)
"?" is unhelpful. If you have a question about what I wrote, ask it.
make damageamount this
public void DamageAmount()
{
return damageAmount;
}
then call it using
bullet.DamageAmount();
try that
alr
Not sure how that changes anything
he said it's a property but I don't see him calling it with parentheses
but isnt it easier just to make it a float which i did
Properties are not called like methods
idk what a property is
i think damageamount is an attribute
It's likely a field, but regardless, if it was a property it's still invoked the same
It's not an attribute. All of this is irrelevant anyway. You haven't debugged whether any of this is being called at all
yea
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed;
public float damageAmount = 1.0f;
[HideInInspector] Enemy enemyScript;
void Start()
{
enemyScript = FindObjectOfType<Enemy>();
}
void Update()
{
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Debug.Log("Destroyed First");
Destroy(this.gameObject);
}
}
} ```
Because you are moving the bullet via its transform it's likely not interacting with the physics engine at all, and the physics messages will not be called.
im not good at physics so i would use addforce?
private void OnCollisionEnter2D(Collision2D other)
{
Debug.Log("Step 1");
if (other.gameObject.tag == "Bullet")
{
Debug.Log("Step 2");
TakeDamage();
}
}
^do that
then tell me what you see in console
if you don't get either
in the bullet script?
Sure, or set its velocity
yes
because its out of the if other.gameobject.tag == "Bullet
Also i never see step 2 when i shoot it
is there a number to the right of it though
the step 1
or no number at all
^ like the 8 there
21 times?
1
shoot it multiple times see if more step 1's pop up
i dont see anything when i shoot it twice
it does
and make sure it's capitalized the same way
is it spelled Bullet exactly?
same capitilization?
yes
hmmm
oh
try changing the oncollisionenter
to a ontriggerenter
OnTriggerEnter2D(Collider2D other)
I think it may not be colliding with the bullet
it's probably just colliding with another random object
and on your hitbox component
check the "is trigger"
also make sure everything has a collider on it
the bullet and enemy
it doesnt even collide with the enemy
the bullet is also a trigger
nvm the enemy falls through the ground
because it has a rb
does your bullet's ontriggerenter work?
wdym?
Yes
does your bullet have a rigidbody?
no
I think for oncollision to work it needs a rigidbody
because it needs to collide with something physics related
but the bullet destoryed when the enemy wasnt a trigger
because ontriggerenter doesn't require a rigidbody
but oncollision does
pretty sure
onTriggerEnter needs at least one of the objects to have a Rigidbody
the Rigidbody can be kinematic if you want though
oh yeah that's right
so i gave the bullet a rb and made the gravity 0 and it collides with the enemy but still doesnt decrease the health
and for OnCollisionEnter at least one of the obejcts needs a dynamic RIgidbody (not kinematic)
does step 2 show up in the console?
no
wait yea
just screenshot
it does
oh nice
but then i get a nullrefrenceexeption for takedamage
then it's working
well that part you need to fix
but that's no longer related to the collision code
but im confused cause it looks right and seems right to me
I don't understand why you have a bulletScript reference on your ENemy class
that makes little sense
so i can acess the damageamount
yeah I was confused too because his system should be flipped
but I went with it
lmao
your bullet should do this:
OnCollisionEnter(COllision col) {
if (col.collider.TryGetComponent(out Enemy e)) {
e.TakeDamage(this.damageAmount);
}
}```
let the bullet handle its own damage and tell the enemy how much damage it took
uhhhhhhh i have alot of questions what is trygetcomponent and out
then run your game and check bulletScript
you should be able to see it on the right when you click on the enemy
if it says "none" then you found the problem
maybe you'll understand this better:
void OnCollisionEnter2D(Collision2D col) {
Enemy collidedEnemy = col.collider.GetComponent<Enemy>();
if (collidedEnemy != nuill) {
collidedEnemy.TakeDamage(this.damageAmount);
}
}```
same thing basically
so?
u used oncollisonenter
ok fixed
doesnt work with 2d
so that goes on my enemy?
nop
it goes on your bullet
it just does this:
when you collide with something, check if the thing you collided with has an Enemy script on it
i would need a refrence to my enemy script
if it does, apply damage to it
The code is getting the reference to the enemy script
right there
Enemy collidedEnemy = col.collider.GetComponent<Enemy>();
it's grabbing it from the collision
this is the right way to get a reference for a collision
alright blue you help him I had my go at it already ๐
Then you just change your TakeDamage function on the enemy so it takes a parameter:
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0)
{
gameObject.SetActive(false);
}
}```
boom done
no weird references to worry about
(and make it public)
OnCollsionEnter2D is red
why
it says Method Must Have A Return Type
yeah you forgot to write void
but wait were you using OnTriggerEnter2D?
and that was working?
you should use that if that was working
yes
the issue was a null
void OnTriggerEnter2D(Collider2D col) {
Enemy collidedEnemy = col.GetComponent<Enemy>();
if (collidedEnemy != null) {
collidedEnemy.TakeDamage(this.damageAmount);
}
}```
I think bulletscript was null
null
what you should do for referencing is just to assign them before you run the game IMO
disagree
in this case you should absolutely be grabbing the reference from the collision
Copy pasting will cause a lot of potential issues; which I'm assuming he's doing due to previous return type issue.
nothing else makes sense for a projectile hitting a target
actually what you should do is just put the damageamount in the bullet code
and do
other.damageAmount
instead of having a separate bulletscript thing
im confused ill just figure it out tmrw
lol good luck
Hi I wanted to ask how I could detect objects in 2D (Im making an endless runner and I want to make it so that there is a chance to spawn powerups in empty lanes)
Cross post from #๐ปโcode-beginner
Please post questions in one channel at a time
Ok sry
hi would anyone be able to help me? my aim is to have triangle prefabs (enemies) spawn just outside the "screen" and as they spawn they would move across the screen. So if they spawn on the right they must leave on the opposite side that being the left (vice versa) An approach i have thought about is; 1. Identify the area the enemies can spawn from (probably need to know screen size) 2. Instantiate the prefab 3. Move the prefab
Sounds like a good approach, go for it
thanks the only thing is i have a rough understanding on how to do steps 2 & 3 im just not quite sure how to go about my 1st step and since its 2D
you can turn a screen position into a world position by using yourCam.ScreenToWorldPoint(0, 0); // would be the bottom left of the screen in worldspace and yourCam.ScreenToWorldPoint(Screen.width, Screen.height); // would be the top right of the screen in worldspace, where "yourCam" is whatever reference you have to the camera
you could then use these two points to calculate the X positions of the left and right spawn, as well as the Y range they are allowed to spawn at
im trying to make a 2d shooter game and i want to make the character to be able to shoot while running
but these are 2 diff animations
how do i go about it
?
is there like a spine for 2d characters
ohh ok thanks, would i also be able to do something like this? i used this code to set the boundaries of the screen for my player object so that it couldnt go outside it ```cs
private float minX, maxX, minY, maxY;
private float playerRadius;
// Start is called before the first frame update
void Start()
{
float camDistance = Vector3.Distance (transform.position, Camera.main.transform.position);
Vector2 bottomCorner = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, camDistance));
Vector2 topCorner = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, camDistance));
CircleCollider2D playerCollider = GetComponent<CircleCollider2D>();
playerRadius = playerCollider.bounds.extents.x;
minX = bottomCorner.x + playerRadius;
maxX = topCorner.x - playerRadius;
minY = bottomCorner.y + playerRadius;
maxY = topCorner.y - playerRadius;
}
void Update()
{
// current position
Vector3 pos = transform.position;
// horizontal constraint
if (pos.x < minX) pos.x = minX;
if (pos.x > maxX) pos.x = maxX;
// vertical contraint
if (pos.y < minY) pos.y = minY;
if (pos.y > maxY) pos.y = maxY;
// update position
transform.position = pos;
}```
yes you could easily reuse a lot of this code, its basically the same logic
you just take the corner positions, grab their X value, and thats the left and right of the screen
so you could just subtract or add some to that X value to make them spawn a little offscreen
depends... is this a hand-animated 2d game? or are you using skeletal bones. Or are you asking if 2D rigging exist? because it does
there should be a 2D rigging package in the package manager that you can import, but it takes quite a bit of setup and decent animating skills to really get the hang of
there are some tutorials online
if it's hand animated at the moment though, there would be no real way to do it without making a new animation that has both attacking and running hand-animated as a new animation
I want to implement a construction mechanic where if you hold the button down on a tile then it "constructs" it, similar to the mechanic in space engineers. Is there a way to apply a prefab to a generated tile that isn't a ruletile during runtime or should I look at making a "tile" class and an instance for every tile, that could then be accessed from a dictionary based on where I'm clicking?
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);```
how can i stop the revolver from going all the way back like this? I want it to flip and be right side up when it passes over the head
if the rotZ + offset is over a certain amount, you flip the spriterenderer on the Y
as in, you use the FlipY property
it might just be rotZ, I dont really know what your offset var represents
alright, well what I said still applies, just without the + offset
sth like this?
well it would be like
renderer.flipY = rotZ > 90f || rotZ < -90f;
I dont know if those values would work though, not sure
i tested them, they should work
then go for it
ight lets see
but the thing is that
you might be missing a negative sign
because if its greater than 90 OR less than 90, thats basically always true unless its exactly 90
Can someone help me figure out a concept for a rail? I have a rail component that has two arrays of transforms. One if the object is coming from the forward direction, and one if it is coming from the backwards direction. When an object hits the rail, I want it to follow the rail, depending on where it landed and which direction it is heading. My main problem is to figure out at which transform in the array it should continue. My idea was to add a direction parameter as wheel as an index in the array to the array, but I am not sure, how to figure out which transform is the next one that the object should travel to
Here is a rail as an example. The yellow things are its transforms in the array and the white thing is the rail itself
How do you guys handle shadows? If I make them transparent, I BELIEVE the left will happen, but obviously, the right would be preferred.
Hey Folks, i try to create a puddle from a huge rain drop on a floor in 2D Space. The puddle is the sub emitter of the raindrop particle system. The problem is, that the puddle appears above the collision ( on the centerpoint of the drop). I dont use a shape on the sub emitter. Is there any good way make the puddle appear on the intersection of the collision ?
Was I clear enough with my question here?
i dont understand technical stuff much but what about having all of the shadows on one layer, render them there without being transparent on (so you end up with right) and then change the opacity of the shadow layer??
Hello Community ,i want to ask Something again how to ignore game object parent transform rotation?, or just make Child object transform always in 0,especially Z axis
Thanks before
Theres a few results if you google it
what is the better way of doing movement instead of transform.translate?
there isnt really a "better" way. Just different ways of movement. physics based or not
https://www.youtube.com/watch?v=tNtOcDryKv4
i just wanna make it so the player doesnt slightly go in to a wall when moveing against it and still be able to jump with a way
watch the vid. it'll explain it
you'll need physics based movement if you want your player to respect colliders
i tried moveposition but it messed with the velocity
Sadly, its not work
If I change the position of an object emitting a trail, will the trail lead from it's old location to new location?
you should probably test it. That's rather specific
I'm changing my bullets from projectiles to raytracing and wanted to keep the "tracer" effect
so my plan is to instantiate the tracer object at the gun barrel and then just move it to hit.point
you mean.. raycasting?
yeah, i'm half asleep right now. don't mind me
again, you should probably test that yourself since you have the means to do so pretty much set up already
it's a bit too specific for someone to have the answer to right off the bat. unless you wait a bit
I'll give it a test, was hoping someone might have known already but no worries :3 i have it all set up on my end
yep, that's how you do it. The bullet object should just be aesthetic -- no functionality attached to it.
well, originally i wanted projectiles but it proved to be impractical for both the players, and for balance
i thought it would, but it doesn't. The type of game it is vs the projectile system makes the gameplay stale when someone outguns you because their projectiles move faster
once taking into consideration the firerate of certain guns and the damage they deal over range, it makes no sense to me to keep a projectile system
Cross posting is against #๐โcode-of-conduct. We know you'll receive faster support but it's not acceptable and cause folks to respond/answer already answered questions.
ok
hey quick question, is there a good way to trigger Invoke() with a keyframe instead of a time?
I'm trying to sync up an attack sweeping animation with a hit detector
animation events
well, it sounds like it's exactly what you're looking for ๐
ye it is, how does one use it?
pog thx
omg it was so easy
i love unity
here i was trying to calculate the exact number of frames between point a and point b
what can i use for simple movment, no jumping. just up down left right
2 simple parts. Detect input. Move object
heres the thing, i dont know how to code
i have this code just to move a circle sprite, but when i use wasd it wont move, can anyone help?
- Is the script attached to the sprite object with a rigidbody2d also attached?
- Did you constrain the X and Y positions on the rigidbody2d?
- do you have any errors?
- Make sure to properly set up your IDE using the steps in #854851968446365696 so it will correctly highlight errors in your script
so i thought i added the script to it already
turns out i didnt
but when i try to add it
it says "cannot add script because script class couldnt be found"
make sure the file name and the class name are exactly the same, it is case sensitive. make sure there are also no errors in your console
so my sprite is labeled as "Player" and the script is called "PlayerMovment"
i have no idea where to find script class
your class is named movement2D
so do i rename it that?
either rename that to the same name as the script file or rename the file to movement2D
wait wait wait, file? what file?
the script, it is a file on your computer. it has a name that you said is PlayerMovment
so do i rename it in unity or do i have to go into the file?
whichever is easier for you because renaming it in unity is renaming the file
ok
thanks it works now
sorry if i was a bother, i havent used the program in years
no worries. i do recommend maybe brushing up on C# using the tutorials linked in the pins of #๐ปโcode-beginner
those tutorials should go over what each part of the script is and how to spot common syntax errors.
also make sure you set up your IDE using the steps linked in #854851968446365696
my sprite wont move
did you make sure to drag the text object into the "moneyText" field in the inspector?
also, set up your IDE using the steps in #854851968446365696
any errors in the console? gonna need more info than it won't move
no errors
can you show a screenshot of your rigidbody2d settings on the sprite object?
Oi. Donโt crosspost #๐โcode-of-conduct
sure
Ok
Sorry
uncheck the x and y boxes in the constraints. those are literally freezing the position on that axis
what is a script i can use for my camera to follow my sprite?
cinemachine
i tried that, but it wont show up
nevermind
so cinemachine is not what i need
it like pulls on my sprite
like rubber
it wont let me go anywhere
cinemachine is exactly what you want unless you want to write your own script for camera movement. You can set the sprite object as the follow target for the vcam. You can modify the body properties to get the follow effect that you prefer
then how do i fix my sprite not being able to move a far distance?
are you certain the sprite is being stopped by the cinemachine camera?
waitr
im so confused
i have it set to follow player
but it wont
i just want to do a script
i hate cinemachine
i think you may be confusing the soft zone for it not following/doing what you want. change the soft zone width and height to 0 and it will always have your player centered in the camera
where is softzone?
in the body settings for the vcam
you need to be much more specific than just "doesn't work"
so i have a cube just off screen
if the cam follows the sprite
then it should show the cube
but everytime i move
i know for a fact my camera isnt following the sprite because the cube never shows up
if you manually move the camera in the editor, does it show the cube in game view? because it may not actually be able to see it if it does not
ive move the cube
and in game view it shows up
will it be easier if i just show my screen?
a screenshot or something that shows what is happening would probably help clear this up
yes
you can just change the file type manually
really?
yes
wait
it doesnt corrupt these files
@lunar quiver If you are in OBS, there's a remux feature to change it to mp4
your video shows that your camera is clearly not following the player so it just isn't set up right
ok
show your vcam settings and your main camera settings
your main camera doesn't have the cinemachinebrain on it and it looks like you are using a 3d vcam
well i clicked 2d
remove the vcam from your scene then right click your hierarchy and go to Cinemachine > 2D Camera. it will add the cinemachine vcam to the scene and should automatically add the brain to the main camera
oh wait
my bad
cinemachinebrain is on my main camera
i just didnt get it
into frame
you sure about that? also the camera you showed a screenshot of isn't even tagged as MainCamera