#🖼️┃2d-tools
1 messages · Page 55 of 1
Whats that thing they need to do so vs registers errors, its like formatting it or something? Because i think Quasar needs to do it
Configure your IDE @still tendon #854851968446365696
ok i go
It should help fix all the typo's and little errors like not uppercasing the i on Input
I better do all the code from the beginning, I've been trying all day to program something that should be super easy
and already configure my vs code for unity
about two hours ago
pay attention to capital letters, {} and ; they're all important
how do i make my 2d character dash?
How could I achieve more efficient procedural 2D generation? For example Terraria large worlds are 16800x4800 and generate pretty fast
Terraria generates the world first into a map file which doesn't contain any objects, just markers where objects will be and terrain data
When playing this data is loaded from the file into chunks that the player is close to
Hmm, so currently my world generates a 2d array with integers for which blocks should be placed and where, could I save this into a json file or something like that and then load parts of it? And if so how could I go about making the chunk loading?
I haven't done this before, but I'm guessing you could use Tilemap objects as chunks
Configure them using the generated data at runtime and load/unload them based on player's distance
When generating large maps, quadtree/octree optimization can be pretty important to keep the amount of data sane
Thanks! After thinking for a bit I think I have a plan,
1 - Generate the whole world in an int[,] and then split it up into chunks and put them in a list (maybe?)
2 - Save this list to a file
3 - Render chunks in tilemaps depending on distance from player
Do you think this could work?
Also, do you think it could work by having one tilemap and using SetTile to add/remove tiles?
if anyone needs to flip something like the transform of a gun barrel for shooting, i just got this working;
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
firePoint.transform.eulerAngles = new Vector3(
firePoint.transform.eulerAngles.x,
firePoint.transform.eulerAngles.y + 180,
firePoint.transform.eulerAngles.z
);
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
firePoint.transform.eulerAngles = new Vector3(
firePoint.transform.eulerAngles.x,
firePoint.transform.eulerAngles.y - 180,
firePoint.transform.eulerAngles.z
);
}
and
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
to actually get the gameobject (firepoint for me), do <name of game object> = GameObject.Find("<name of game object>"); in start/awake
this is for if you arent using brackey's player controller btw
is there any way I could remove a box that was drawn with Gizmos.DrawCube?
https://bzzzzz.has-no-bra.in/55uwQZE1A ignore that its a flying rotating purple bean but how do i make it go faster? im using a* free version
nvm i got it
it means you didnt define GROUND_TAG
and why is your ground part of your background
Possibly! I don't know if there's any downside to tilemaps of massive size
There's a lot of resources about tilemap level generation and saving out there so maybe worth checking out how others have dealt with this challenge
I have already asked in the beginner code channel, but this channel should be more fitting. Anyways I just tried to get a simple top down firing going, but my bullet just wont fly off. It rests in the same place, it is instantiated.
This is my code.
And this the rb of the bullet.
I am pretty new to unity, but have you tried using rb.velocity instead of rb.AddForce or do you want to use AddForce?
and, if you want to use addforce, maybe have a position offset to the bullet when it shoots depending on the direction of fire
rb.velocity wont do the trick for me either.
How would I go about that?
When you instantiate the object, have the position like +10 or something
wait does the bullet disapear, or does it just stay in place?
It just stays in place
oh
Maybe it gets stuck at the player?
does the player have a solid, non-trigger, collider?
This is how it looks atm. Green dot is the player and pink triangle the enemy. Blue dot the projectile
The enemy has a non trigger collider
Hey guys, I want to get a point in a direction based on the rotation of another object... I have no idea how to do it but I have been trying to use
float rot = playerSprite.transform.rotation.z;
rot = rot * Mathf.Deg2Rad;
if (Mathf.Abs(h) > hDeadZone) //If choosing to move
{
hSpeed = Mathf.Cos(rot);
vSpeed = Mathf.Sin(rot);
}
Debug.DrawRay(transform.position, new Vector3(hSpeed*0.5f,vSpeed*0.5f,0),Color.red);
So maybe
transform.rotation returns a quaternion, you want eulerAngles instead
I want it to be, when I press left, my character moves a specified amount, in the left direction of the sprite, but not it's pwm object
ahhhh
thanks
No, that wasnt it either.
oh jeez, thanks a heap @late viper
hey, for the game im working on atm (my first game ever) I have made "force bullets" that work almost exaclty the same as your bullets, but for a 2D platformer. These bullets only push things around. Do you want me to send you the code for them?
That would be great!
you want me to dm it to you?
Yes
Hey all, i have bullets in my scene which move by velocity. I want them to slow exponentially slow down over total range regardless of how long the range is. I've tried alot but cant figure it out.. Any ideas?
that won't compile, velocity is a Vector3 and you're trying to set it to a float.
oh wait...
I see what you're doing.
var v = rb.velocity;
v.magnitude = Mathf.Lerp(maxVelocity, minVelocity, distance / range);
rb.velocity = v;
rb.velocity = rb.velocity.normalized * Mathf.Lerp(maxVelocity, minVelocity, distance / range);
Hey uhhm I´m currently working on my first 2D-Plattformer and wanted to ask if there is any way to make it so that the box collider of a Sprite always automatically matches the Texture of a sprite and not the size of the Sprite itself.
How do I make a script that changes rule tiles to count anything that is one the same tilwmap as them as neighbors?
So that it doesnt just count itself as a neighbor, but also any other tile that has been placed on the tile map
Does anyone know?
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 can i apply my code to the y axis aswell?
ive been trying withn no succes
its an enemy mover script btw
transform.right = aim - (Vector2)transform.position;
For some reason this modifies the x rotation when it's only supposed to change the z
(2D game)
Or if that's intended behavior how do I prevent it of doing that, I tried that:
Vector3 eulerRotation = transform.rotation.eulerAngles;
transform.rotation =
Quaternion.Euler(0, eulerRotation.y, eulerRotation.z);
AND
transform.rotation =
Quaternion.Euler
(0, transform.rotation.y, transform.rotation.z);
Both not working for different reasons
(First one does nothing and second one prevents z rotation)
I need help, Been stuck for 2 days trying different ways to fix my issue. I have my two scripts below. one is my timer script and the other is my stat script. The code below my timer allows me to store my timer in a format that I turn into a string on my stat screen. So I have figured out how to store the longest run time but now I am trying to add up all run times and I cannot figure out how to add up the numbers. When I try adding them the numbers go above 60 for seconds an above 100 for milliseconds.
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.
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.
additional visualization of the problem
You should just store it as milliseconds and convert to seconds/minutes/ whatever when you need to display it
So create another int called Total Time under my timer += Time.deltaTime that just calcuates milliseconds. store that number to a playerprefs?
What would be the math equation to convert that number to minutes, seconds, milliseconds?
https://forum.unity.com/threads/converting-seconds-to-hours-minutes-seconds-for-count-down-timer.861388/ Here's a thread related to that
So I read through twice. Boy myhead hurts
Thank you guys so much. I got it figured out, changing my original mess of a code for saving longest run time. The Link really helped the the advice about converting a single type of time like milliseconds save my rear end.
I am so close to finishing and publishing my first game. pretty excited. Maybe one or two people will actually download it lol
is there a way i can get my camera to smooth zoom and position on a game object, like in the game over screen in mini metro?
easiest way is Cinemachine
but scripting it yourself is also not that hard.
Hi guys, does anyone know any way i can save my information into a text file on webgl? i tried doing that but my game hangs after build
File IO should work fine on browsers, they generally just have their virtual filesystem.
I know this is super simple, but I'm making a sort of Pong clone just for display, and I want all the elements to be the same pixel dimensions, just the area of play to be bigger, at all screen resolutions. How do I go about this?
I need help with something , and that something is that i need help with rotating sth
So ,
There is "Object A" and "The Player"
I want to make it so wherever i move my mouse on the camera , "Object A" orbits "The Player" with on a circle with a set radius .
Any way i can manage to do this?
What is the mouse affecting?
Im basically trying to recreate the game rotmg if u know it .
I made a system where you can rotate the camera with Q and E
And you can move around with WASD obviously
Im making it so that i fire where i point my mouse at .
So you want the object to rotate around the player
At a set distance
yes
I want to rotate the object , on an orbit of a circle which its radius is a set value , based on the location of the cursor on the camera
here is a brief explanation
that red thing is the object ,
that gray circle is the orbit path ,
that in the middle is the player .
Yeah but from what i get , Rotate ADDS rotation to the object while i want to directly SET the rotation
Habla no ingles
Set up your hierarchy like this:
Player
Pivot (local position 0, 0, 0)
Camera (local position 5, 0, 0)
Point the camera at the player, then rotate the pivot
then in your script you just rotate the pivot and it works
yo i want to add recoil for my game, i want to make it where you point a shotgun down and shoot, then it pushes you up in the air
not like anyone needs an explanation by what i mean but heres one
Use rb.AddForce(yourForceVector, ForceMode.Impulse);
make a script for that?
Probably would put it in your script that handles firing the fhotgun
syntax rules of C# must, of course, be followed
i dont know what anything of scripting means so idk what that means
C# (the programming language you write Unity scripts in) has rules
your code isn't following those rules
and so it can't be run
You might want to start by looking at the pinned messages in #💻┃code-beginner to learn some basics
your rotation is wrong because I guess your standard 0 rotation is messed up
I dont know, it looks like your camera is rotating, is that intended?
yeah, that rotates around 100, for whatever reason, so it is intended, yes?
YOu should know, what are you trying to rotate?
you are trying to rotate the player?
The camera is attached to the player, right?
Thats your issue, just make a smooth follow script for the camera, then you can just flip the player either with 180 or just localscale.x to -1 and 1
As long as your camera is attached to your player, it will rotate too and therefore look weird, look at your scene view while playing ,you will see your camera fly off
I wrote everything you need to know 😄 detach camera, make it follow the player with a script, in your flip code, use 180 for y rotation or just localScale.x to -1 or 1 depending on the direction
Thats a REALLY EASY and REALLY SMART idea . Thank you SO MUCH!!!
does anyone happen to know of any videos or pages that have info on how to make a pokemon dialog system? or does anyone know code to accomplish that? i have a dialog system that pops up and shows the text, but what i am wanting also is how in pokemon, the letters popup 1 at a time as if its being typed, and then if its a long bit of dialog, the player can click to go to the next page of dialog
Basically TextMeshPro gives you the maxVisibleCharacters property which will do what you want
so i couldnt get the script to work, theres no errors, when when the TMPro gets activated, it just shows the whole text
i found another script though im going to try
you should just update the tmpro text with your own function. Get the text, its an array of letters, think of it like that. Now you can first string.split with whitespaces after some certain length and then take that part of the array and split it into its letters and then jus tshow one by one with a coroutine for example
ok so i got the slow revealing text working, but still not quite understanding the page system
line 22
you're trying to assign playerposition.x, which is a float, to tempPos which is a Vector3
Also you need to get your VSCode configured properly so it shows those errors. You can find instructions in #854851968446365696
I already installed all the extensions and the .NET
Did you do the rest of the steps?
I've got an issue where my Sprite Renderer of a specific Game Object isn't responding at all to what I put in my Update Function, I'm just trying to enable and disable it at specified conditions, but it won't respond to anything
i tried to enable/disable it at the beginning and the end to make sure any other functions that are called in Update doesn't mess with it
I also looked at every keyword for "Sprite Renderer" in all my files to make sure it didn't change anything
Once I enable or disable the Sprite Renderer in the Unity Editor and press play, that'll be it's value for the rest of the game
I'm wondering what factors might lead to this problem? I do use Coroutines a lot, but only one of them disables the Sprite Renderer, and my problem is that whatever value I set it in the Unity Editor is what remains throughout the game
and I haven't used the Sprite Renderer Property in any of the Animations as well
I enable and disable it at the same time with my Polygon Collider for the Game Object, and the polygon collider enables it at the correct moment, but the Sprite Renderer doesn't change
TLDR: Game object in question is just a spear my boss holds, it's animated alongside the boss using sprites and transform, and I want to make it visible when their health is low
Collider is enabled at the correct moment, Sprite Renderer is not
Update() has no influence over Sprite Renderer, suspecting it has something to do with Animator, but checked that Sprite Renderer Enabled property isn't in any of them
Been trying to fix this since morning 😩 , if anyone knows anything about how Sprite Renderer might be enabled/disabled or how it's called please lmk
For some reason, the built version of my game runs differently than the editor version of my game. Does anyone know why?
try doing .SetActive(false) instead of disabling
The Entire Game Object? It ended up being the same result where it won't be changed during the game but I can assign it's value in the editor
can you show me the conditions and the code you are using to hide it?
yea! Here it is in the start function to make sure it's off temporarily
here's the update function
It's enabled in !spearThrown, and when Phase 2 begins at else if ((health <= phase2))
it's disabled when ThrowSpear is called, and spearThrown is set to True in a gameobject prefab while it still exists
phase is called in the update function and changes based on the health of the boss
they're both called at the right time when I put a debug log there
ok I notice you do
spearHold.GetComponent<SpriteRenderer>().enabled = true; if phase is 1
but you don't do
spearHold.GetComponent<SpriteRenderer>().enabled = false; when phase is not 1
is this an oversight?
spearHold works fine, spearTailHold is where the problem is at, mb it gets confusing with the names
I want the character to hold the spear in phase 1 with his hands, phase 2 and 3 he holds it with his tail
works fine with spearHold, not spearTailHold
this isn't really a solution, but if you are calling GetComponent so much you should probably just set a reference before start
so you don't have to GetComponent everything you use spearhold or spearholdtail
ohh right, ty for the tip
yep both are game objects
why doesn't the setactive method work again?
pretty much identical, aside from being animated differently and that spearTail has a collider
I'm not sure myself
so you have 2 image essentially where one image he holds the spear in his hand and one in the tail right?
They both have different Parents, and the parent of Tail Spear occasionally gets .setActive(false) if that has an influence
they're the same image just placed and animated differently
this doesn't affect children
parent getting set to false doesn't affect their active status directly
i.e. when the parent is turned to false, everything underneath is false but they retain their true/false so that when the parent is back to true, the children will be what they were before the parent was turned off
but obviously something won't be active if the parent is not active if that's what you meant
makes sense
can I see the hiearchy of the part your issue is at?
like what are the parents/children of tailspearhold etc.
also I don't know if this is an option, but I would just switch everything to setactive instead of enable
but if that's not an option then it makes things harder
sounds good, is there any coding benefits other than simplicity for that?
I think it's just good practice
and there isn't really anything you can't do with setactive
can I see where you set SpearTailHold?
like when i declared it?
also if you have more than one sprite renderer that may be the issue
yes
honestly just change all your enables to setactives and see how it goes from there
public GameObject SlashPrefab;
public Transform TopCenter;
public Transform BottomCenter;
public Transform BottomLeft;
public Transform BottomRight;
public Transform TailLocation;
public GameObject SpearHold;
public GameObject SpearTailHold;
public GameObject Arm;
public GameObject Claw;
public GameObject Tail;
public GameObject TailPoint;
public GameObject SpearTailPoint;
public GameObject Head;
public GameObject MasklessHead;
public GameObject Mask;
public GameObject Red;
public static bool FightBegun;
does tailspear only have one spriterenderer?
seems so
if nothing's wrong with your code setactive should make your problem a lot easier to solve
but I think it might be with the code
i'll give setative a try tomorrow
if you want u can just dm me every place that is related to settailhold
every place of code
so I can track the problem down
oo ok, i'll let you know then if I still haven't solved it until then
kk
thank you for helping!
I'm actually using this for UI but I don't think this is really a UI question: I've brought in a 22x20 spritesheet and imported it as a sprite asset with all the slices in the right place etc. In code, what's the right class to use to load this up, see how many frames it has, access individual frames etc?
How do you access the size of a collider? I have a reference to the collider but cant seem to find the right path to the size
Maybe you are looking for Collider.bounds?
Thank you, that seems to be the right thing, but how do I modify it?
Cannot modify the return value of 'Collider2D.bounds' because it is not a variable
I get this error when I try to assign a value to it
I tried
collider.bounds.size = ...;
Is it possible to modify the values of bounds.min and bounds.max?
And you can only change .size/.center property on the default simple collider types.
What are default simple collider types? I am doing it on a capsule collider
Thanks I will try this
The bounds is generally derived from the shape properties
A capsule collider has height and radius
When in doubt, looking it up in the manual. https://docs.unity3d.com/ScriptReference/CapsuleCollider2D.html It also lists basic types in the base class page.
I have a problem with this, the first two lines work but the last one doesn't.
I tried:
m_CrouchChangeCollider.bounds = p;
And
m_CrouchChangeCollider.bounds.size = p;
But I get the same error I got at the beginning
Actually I think I fixed it
Instead of referencing a Collider2D I referenced a CapsuleCollider 2D and that does seem to have a size parameter
And does anyone know how I can modify what a rule tile counts as a neighbor?
I want it to count anything that is one the same tile map as the rule tile itself
I've got a 20x22 sprite sheet that all looks fine in the inspector, and if I scroll through all the sprites under it, the animation is playing in the right order, BUT...
sourceRect = allSprites[frameIndex].rect;
frameIndex++;
frameIndex %= allSprites.Count;
Doing that, the frames seem to be playing in the wrong order. Is there an obvious thing I'm doing wrong?
Looks like it's playing the rows in the wrong order, but the columns within that row in the right order. What?
Hey, so I have this 2D animated character, and I would like to make color variants of it without re animating the same things with differents sprites for every variation
is there a work around ?
I remember from using other software that the coordinate system might be different in textures
Might not be your problem but it sounds like it
like x going left when bigger
In the end I just decided to do this:
var assets = AssetDatabase.LoadAllAssetRepresentationsAtPath(SpritePath);
allSprites = assets.OfType<Sprite>()
.OrderBy(s => s.rect.y)
.ThenBy(s => s.rect.x)
.ToList();```
then it's fine.
I made a custom rule tile script and Im trying to achieve this but all that is inside the script by default is this:
public bool customField;
public class Neighbor : RuleTile.TilingRule.Neighbor {
public const int Null = 3;
public const int NotNull = 4;
}
public override bool RuleMatch(int neighbor, TileBase tile) {
switch (neighbor) {
case Neighbor.Null: return tile == null;
case Neighbor.NotNull: return tile != null;
}
return base.RuleMatch(neighbor, tile);
}
}```
And I only see the method where you can define when a rule match is true, but I dont see anything that can help defining what a neighbour is
my code for the spriterenderer size is this
FightBottom.GetComponent<SpriteRenderer>().size = new Vector2(8, 1);
so first off it might be because you didn't put in the parenthesise at the end of bounds or maybe because you should've used a vector for it. it works for me, so if it doesn't for you, i'm sorry
Thanks, but I already got it to work, it worked when I made the collider be a CapsuleCollider2D instead of a Collider2D
Currently my problem is this
oh
I have diagonal wall sprites in my tileset, that i'm using transparency sort axis with. it works fine, however the diagonal walls cause some issues
because the sorting is based on y axis and they're diagonal, the player sprite can clip through them if they move close to the top part of the sprite
since it's diagonal, the character sprite goes higher in Y than the center of the wall sprite, and the character gets sorted under it automatically
how can i fix this?
isometric, sorry should've mentioned that
pics for clarification, here its sorted correctly
and here it gets sorted under, because it moved diagonally along the wall to a higher Y position
will the player sometimes be behind said wall ?
yes
maybe just put the center of the player at it's feet
that way his position is calculated from that
it is already
actually nevermind, I don't think it is
i'll try that
how can i change all the pivot points of sprites of a sliced spritesheet at once
so, that didn't work, the position is apparently not calculated from the sprite's pivot point but the center
which is stupid in my opinion, btw
apparently unity WAS smart enough to think of that :)
I am trying to make a UI button spawn randomly
Vector3 randompos = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), 0);
Debug.Log(randompos.x);
GameObject instance = Instantiate(targetPrefab);
instance.transform.SetParent(canvas.transform);
instance.transform.position = randompos;
instance.SetActive(true);
The debug log logs for example 86 but the real position of the button is -883. Anyone know why this might happen?
UI uses screen coordinates. You’re setting world coordinates. If it’s a UI, you should position it using the recttransform’s anchored position
When I resize the box around a TMP Text object by hand, what is being modified? The RectTransform's width and height aren't changing at all. (But if I change them manually, the box does resize, but only a little. There doesn't seem to be a logical connection)
the anchor offset stuff which... is different depending on what your anchors are
unless it's the yellow box
in which case that's the margins
yes its a yellow box
which you can find buried in other settings or something
yeah it's the margins - that tripped me up a bit recently too
hm ok, I'll look them up
heh. this RectTransform / TMP stuff seems needlessly complicated
oh I see.. there's a yellow box and a white box.
the white box is the width/height and the yellow box is the margins relative to it
they overlap perfectly if margins are set to 0,0,0,0
yes
if im making a 2d player gameobject, do i put the hitbox as the external component and put the sprite as a child of it or the other way around?
what's an "external component"?
I usually do someething like this:
Player (main scripts, Rigidbody2D)
Visuals (empty, can be rotated to rotate whole player)
Collider (Collider2D)
Sprite (SpriteRenderer)
Other stuff
Anyone has any tips on how to make a good stickman ragdoll which moves using physics?
hi this is a sprite with some particle system on it, can i make the particles sorted so the particle that is on his foot render in front of him and the others above the legs behind it? or should i make 2 different particle systems just for this?
I would like a script for boiling a lobster in a 2D game.
lobster2D.boil()
perfection
Not you.
nah nah nah, that's not scalable. You need to do lobster2D.SetState(State.BOIL)
That's what's in the boil() method. It's a non-parametric overload for use with Invoke
if (lobster.isAlive) {
lobster.stepBoil();
} else {
person.eat(lobster);
}

What are you doing, stepBoil()?

I want to make recipes.
good on you?
I want to make a game similar to Cooking Mama, but not exactly like it.
What is your actual question, making minigames like cooking mama is a whole set of various actions. You need to decide on what you're going to actually make.
public Input Controllerleft = Input.GetAxis("Left Analog Stick (Horizontal)");
Could someone help me figure this out I want to add controller support but no clue how
GetAxis just returns a float indicating the current value of the axis
not sure what you're trying to do with that Input field situation. Doesn't work that way
I can switch from Input to KeyCode but that just makes a different error
If you use GetAxis you have to have the axis defined in Project Seettings -> Input Manager
Do you have Left Analog Stick (Horizontal) defined in the Input Manager?
And again - you just read the value as a float, it doesn't return an Input object
and either way, that call needs to happen inside a method, not floating somewhere not in a method
So it returns as a number instead?
yes, it returns a number. See the manual for more information: https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
@snow willow Hey you probably don't remember me, but 4 days ago you helped me realize that I was feeding a position vector into a slot that needed a direction vector and I wanted to thank you.
not a problem!
{
print("hi");
// force is how forcefully we will push the player away from the enemy.
float force = 50;
// If the object we hit is the enemy
if (c.gameObject.tag == "enemy")
{
// Calculate Angle Between the collision point and the player
** Vector2 dir = c.contacts[0].point - transform.position;**
// We then get the opposite (-Vector3) and normalize it
dir = -dir.normalized;
// And finally we add force in the direction of dir and multiply it by force.
// This will push back the player
GetComponent<Rigidbody2D>().AddForce(dir*force);
}
}```
I'm trying to move and object the opposite directions of what another object collided with it at. I got a error on what was bolded. I copy pasted the code from another website btw.
Vector2 dir = c.contacts[0].point - (Vector2)transform.position;```
C'mon please help me make a similar game to Cooking Mama?
What chu got so far?
I wanna make a game similar to the game "Cooking Mama"
We can't help you if you just say that. We're not going to tell you how to make a cooking mama game step by step if that's what you're asking
Please?
No.
Be nice.
It's not me being not nice, its literally impossible for me or anyone else to do that
You need to decide what you specifically want in your game, and build it bit by bit. No one here can do that other than you
Go on fiverr someone might do it for 10$ xD
I'll do it for $20
Damn, have some standards people
It'll be a really bad game

I wouldn't suggest posting shady exes even as a joke, it might get you banned lol
I doesn't work.
Bruh
PEGASUS
Try restarting your computer
It still doesn't work. I need a ZIP folder.
Ye prob, but I can't upload such a huge file on discord
They're trolling you. Please dont be this gullible on the internet or you're inevitably going to get malware on your computer
@late viper U sure he ain't trolling us
I'm not being gullible nor going to get malware on my computer.
he's been begging for code for years on this discord, it would be a very long con
No, I haven't.
you just tried to download a random exe on discord, that is very guillible
Nah... you just miss your mama so much
No, I didn't.
That's a lie.
if you say so 🤷♂️
@alpine swan Don't send random exes and don't post reaction gifs
Sorry ):
hi i need help with state machine behaviours
so
in a behaviour script how can i get the rigidbody componenet of the game object to which the behaviour is attached
hey
get the gameObject from the animator component, then GetComponent the rigidbody
how do i get the game object
see
if i use findobjectwith tag
it will break
so this thing is an enemy
and i want get its rigidbody to move it
but if there are two enemies with the same tag
it wont work as it will get the rigidbody of the srong enemy
you understand?
no
so see
I have two enemy
both have ta enemy
now if use findObjectwithtag(Enemy)
it may get the wrong enemy
i want it to to get the enemy to which the behaviour is attached
Which behaviour?
Hello, I need help with a boiling minigame for a cooking game.
I don't think you can do that
Please answer me?
its possible. Just do whatever you want to do when you ask the animator to play the attack animation
from a Monobehaviour rather than a StateMachineBEhavior
the animator parameter is referring to the animator. get the gameObject from the animator using .gameObject, then it's just like any other GameObject
oh I see
i'm assuming they're using the predefined methods when inheriting from StateMachineBehaviour
I want various actions like Cooking Mama, please.
I want all the steps from cooking Mama.
😂
No one's stopping you ^^
So let's see what you have so far?
I will be stopped if I get a script.
Oh, you're asking for it to be done for you?
Yes.
Don't spam this discord with that nonsense. If you want to hire someone, there's a section in the forums. Find the link in #854851968446365696.
I'm not.
Well, this isn't the place to ask for handouts. Unless you're going to show your work, so people can help you with issues, don't post about this again.
That's rude.
That's the rules. You're not a special case to be exempt from them.
hit doesnt exist, what do i put instead
What are you even trying to do?
I assume you want to raycast from the mouse position?
so
im trying to
uh
so i have an object
i want to make it interactable
i got a script for interactable
public class Interactable : MonoBehaviour
{
public float radius = 3f;
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, radius);
}
}
not done
yet
but it says radius and stuff
but i now need to add it to my player controller.. So when i right click it sees whether its interactable
i think thats what im trying to do
lol
ah alr
Specifically using raycasting from the mouse position into the world. Getting the object the ray hits and checking if it is a Interactable, as you're already doing.
alr
thanks
o noes
@abstract olive help
i got rid of that, cause i was gonna do it in another script
but now my fixed update isnt working
why?
apparently its declared but never used
and its back to how it was b4
?
public float speed;
public float turnLimit;
bool swingingLeft;
Rigidbody2D rb;
public float waitAtLimit;
float currentCooldownTime;
private void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
currentCooldownTime = waitAtLimit;
}
private void FixedUpdate()
{
if(swingingLeft)
{
if (rb.rotation <= turnLimit * -1)
{
SwitchDirection();
}
}
else
{
if (rb.rotation >= turnLimit)
{
SwitchDirection();
}
}
if(currentCooldownTime <= 0)
{
if (swingingLeft)
{
rb.velocity = new Vector2(speed * -1, 0);
}
else
{
rb.velocity = new Vector2(speed, 0);
}
}
else
{
currentCooldownTime -= Time.deltaTime;
}
}
void SwitchDirection()
{
if(swingingLeft)
{
swingingLeft = false;
}
else
{
swingingLeft = true;
}
currentCooldownTime = waitAtLimit;
}```
I have this script to make an object that has a hinge collider 2D swing to the left and right until it hits a certain angle and then change direction. The script works but when I try to connect another object to that object that is supposed to swing with it, it breaks and over turns
I did the probably most obvious thing and made it a child object of the swinging one, but that also makes it rotate with the parent object which I am trying to disable
Hi, im new to unity and programming so i have a lot of problems with my code. Is this the place where i can ask for help ?
#🔎┃find-a-channel pick the channel most relevant to your questions
if you're new, it's most likely #💻┃unity-talk for non code issues, and #💻┃code-beginner for the rest
Alright, thanks
how would i go about pausing my players movements until i press a key? making a flappy bird type game and dont want the player to start falling right when the game starts but only when i start pressing the space bar
Set timescale to 0 at the start and disable your player movement script at the start.
Set timescale to 1 and enable player movement after the player presses a button.
awesome, thank you!
Hello! I'm having some trouble trying to figure out how to set up proper camera borders with the pixel perfect component. I was thinking of creating a border the size of the camera ortographic size, but I don't know how to approach that.
what's a camera border
A border the player collides with so he cant get out of bounds
Hello, I'm trying to drag one prefab. but if i'm out of the Collider, it stops moving, is there any way to save the collider I touched and transform his position even if i'm out of his collider?
if(!_dragging) return;
var fingerPos = GetFingerPos();
Vector2 touchPos = new Vector2(GetFingerPos().x, GetFingerPos().y);
if(GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos)){ //Pretty sure the fail is here
transform.position = fingerPos;
}
}```
is there any way to save the collider I touched
Have you discovered the magic of variables yet?
Hi
so i want my enemy to not collide with the player
as in go through it
but i want it to trigger a player damage function
how do i do that
check the trigger box in your collider then use OnTriggerEnter2D in code instead of OnCollisionEnter2D
What does setting SpriteRenderer.color do under the hood?
Pretty sure it sets a shader parameter
Right, so it will create a new material instance?
nah
Renderers have a certain amount of leeway (somehow) to set shader params that override the material settings
which is why you can do stuff like this: https://docs.unity3d.com/ScriptReference/Renderer.SetPropertyBlock.html
And in it I removes all of my SpriteRenderer.color assignments and replaced them with shared materials of various colors
And this at the time reduced draw calls significantly
But unfortunately I didn't make very good commit messages
I mean I don't think it does but should be pretty easily testable
Hi
rb.addforce doesnt work
I want to do knockback
btw i am using rb.velocity for player movement
and i want to add knockback to player
You override added forces when you use rb.velocity
You either need to use forces for movement or handle the forces manually with your rb.velocity
calling AddForce will not do much if you run it for a single frame. The "force mode" argument allows you to use different force modes (which may be more appropriate)
hello, i dont want my ball to pass through this box when its droppingm how do i do that?
I want an object to follow another object exactly, but without changing the rotation when the object it follows changes the rotation, so I cant just make it a child object of the object I want it to follow. I made a script that changes the position of the object to the position of the object I want it to follow each frame, but it looks a bit wonky. Is there a better method to do it?
Try using the Position Constraint component on your follower instead.
So I would make it a child object and use that component?
Nope. The point of the various constraint components is so you don't have to child it.
And how exactly does it work?
I have given it the position constraint component but Im not sure how I can use it to make it follow an object
Oh never mind I see
The sources seem to be what I need
Thanks!
hello
so I made a physics system with Transform's for fun
It works well but has one problem
the player sinking 0.08 units into the ground
its not much but its noticable
https://youtu.be/uTS0CXMtjwk
here's the bug
What exactly do you mean by "physics system with Transform's"?
a powerful website for storing and sharing text and code snippets. completely free and open source.
Transform.Translate down
really dumb and basic but it works
And why dont you use a rigidbody?
Its a small prototype
rigidbodies are pretty cool
anyone know how can i change the pivot point in the script ?
@merry tundra take a look at the sprite import settings, there's a pivot setting
I'm working on a BOIDs test scene and I'm stuck on getting them to avoid each other. Hoping someone can help with this vector math
I have a BOID that knows it's position and the position of it's nearest neighbor. What I want is to tell the BOID to turn away from it's nearest neighbor. Given the two vector points, how can I tell the BOID which way to rotate?
I'm working with Vector3.Dot but it's only able to tell me if the object is in front or behind, not left or right
i need to control it by script
ah I see
one sec
sorry mate seems like that's not straightforward, this is the most useful thing I found
idk your needs but maybe you can just set up an array of several sprites and have a different version for each pivot point?
best of luck
thx bro
By how much do you want it to turn away?
my thought is that I can factor in the Vector3.Dot
so that it turns away by a set speed, and moreso if it's pointing directly at the object
You could rotate the vector around the Z axis based on whether it is heading to the left or to the right of its neighbour
I guess my issue is determining whether it's left or right
Dot product should say that right
Based on its sign
If not then use Vector2.signedAngle or something along those lines
hm maybe I need to better understand dot product
Hey guys, I can't get Classname.Instance.gameobject !! Any idea why not??
wouldn't directly left and directly right both return zero from dot product?
@still tendon can we see the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIController : PhysicsObject
{
public float aiMaxSpeed = 7;
public float aijumpSpeed = 7;
public float aiDirection = 1;
public float aiChangeDirectionEase = 1;
public float aiDirectionSmooth = 1;
private bool isAIJumpping;
public float playerDifference;
private Vector2 raycastOffset;
[SerializeField] private LayerMask LayerMask;
[SerializeField] private GameObject _aiGraphic;
[SerializeField] private Animator _aiAnimator;
private RaycastHit2D aiLeft;
private RaycastHit2D aiRight;
protected override void ComputeVelocity()
{
Vector2 aiMove = Vector2.zero;
playerDifference = PlayerController.Instance
}
}
On how to format your code for discord
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIController : PhysicsObject
{
public float aiMaxSpeed = 7;
public float aijumpSpeed = 7;
public float aiDirection = 1;
public float aiChangeDirectionEase = 1;
public float aiDirectionSmooth = 1;
private bool isAIJumpping;
public float playerDifference;
private Vector2 raycastOffset;
[SerializeField] private LayerMask LayerMask;
[SerializeField] private GameObject _aiGraphic;
[SerializeField] private Animator _aiAnimator;
private RaycastHit2D aiLeft;
private RaycastHit2D aiRight;
protected override void ComputeVelocity()
{
Vector2 aiMove = Vector2.zero;
playerDifference = PlayerController.Instance
}
}
sorry
Does your PlayerController script have an Instance variable?
how did you do that?
Now that I think about it I think dot product doesn't give info on left or right
@still tendon #854851968446365696
sorry, silly me!!
forgot making get{}
for new instance
got that! 👍
Quick question guys, how can I refer to these sprites via single GameObject
Every part name is a sprite
Just have a reference to the parent object and if you want a child you can use FindChild, GetChild, etc
Guess it depends what you want to do with them
In similar situations I've used GetComponentsInChildren
thing is, I'm checking for flipping sprites on left or right and if there are more than 1 sprites it doesn't work that way
GetComponentsInChildren returns only first child object!
The plural version will return an array of matches.
Well, an array of components rather
And from all children, even recursively
sorry had no idea there was a plural version!😅
Is anyone familiar with rule tiles? While defining individual rules, does the order matters?
I'm generating them through the code, and it seems it matters.
Also looking at the inspector, the rules are draggable, I'm guessing for the same reason.
Yes
How would I go about generating a custom mesh and using it as a sprite mask?
so when i jump the entire level just dissapears, why?
this didnt happen when the camera wasnt following the character
example of what is happening: https://gyazo.com/ec46ed2a824e3e0f5e695b97ed105e76
and this is the code
how do you make transition between rooms like binding of isaac?
creating scene for every room (i dont think so) or using panel for 0.5 sec make everything black then teleport to other room
or anything else any ideas?
i'm guessing it's because you set your camera z to your y, it goes behind the scene, so you cant see anything?
How you make the rooms is a different consideration, but you could create a cinemachine virtual camera in every room and enable it when you want the camera to go there
I can't recall how isaac does it
instead of creating virtual camera in every room i can change position of camera
that is how you change camera positions in cinemachine
a "virtual camera" is a camera position
Yea virtual cameras are "changing the position" on steroids
I'm making an isaac clone, though I'm only using the basic sized rooms like in the flash version. What I do is lerp the camera to the room center point when I change rooms to give the feel of actually moving between rooms rather than just teleporting the view
hi, i'm curious, how are you generating the rooms? is it pregenerated?
The rooms themselves are pre-designed layouts, but I am generating the dungeon at runtime to make unique floor layouts.
I put the room objects into arrays on a script able object that my dungeon generation references and instantiate the room objects and grab the layout from the array. Although I may look into writing a script to generate the layouts of each room at runtime depending on how bloated the current method gets with more room layouts
i see. thank you for sharing
Any suggestion where I could find a tutorial that explains how is the order used in the algorithm? Thanks!
Even if I check the Unity official tutorials, they never mention that the order is important.
Found this in tilemap extras, but it's not clear: "For optimization, please set the most common Rule at the top of the list of Rules and follow with next most common Rule and so on. When matching Rules during the placement of the Tile, the Rule Tile algorithm will check the first Rule first, before proceeding with the next Rules."
Think of it like if statements, it checks each condition in order. So it will perform fewer checks for the most common ones if they are higher in the list
so im working on a little project in unity (v.2020.3.15f2 64-bit) and im having a hard time with making a movement script in bolt what i need to know is how i move the player 5 steps forward relative to its position can anyone help?
There is a visual scripting server #763499475641172029
awesome ill post the same question there
it appears everyone there is offline
I've store a grid in a Array2D and want to detect his limits for doesnt letting anything move out of that array grid, PraetorBlue told me using that array2d as information instead of physical collision, but I didnt find out anything out on the internet, anyone has a link for learning how it works or know how to do it?
2d array you can get the limits with myArray.GetLength(0) and myArray.GetLength(1).
so you just make sure the x and y coords are > 0 and less than that length
as for colliding with other tiles in your grid you just check if there's a tile there already.
i'll try, thanks for the tip
I would like to make a game with the same steps as Cooking Mama and Cooking Academy, but I don't know the scripts.
Sorry, i can't make it work. since the Grid its in another script, i'm using GetComponent<GridManager>().Grid.GetLenght; but it sends me an error and dunno how to write everything clean and also if i write everything in the same script I dont know how to detect if there's a tile or not around... i'm feeling totally defeated
errors are there to help you know what is wrong with your code. post it and someone can help you identify what it is and hopefully you'll learn how to fix similar errors in the future
Looks like everything it's okay
but then
I have no idea what is the error hahahah
I'm dying right now, every thing I do it has a new error aaaaa
Not sure if it's the cause of the current issue, but I believe line 28 should read tempPos.x = player.transform.position.x;
I solved
It was because I removed the player before and forgot to add the player tag to the player
god
I'm so noob at this
How do I turn a sprite sheet into a pallette?
k
so you must select it
and in inspector you must change single to multiple
and then slice it in sprite editor
now it depends if you want normal palette or pallet with rule tiles
@languid adder
rule tiles are tiles, that are in script, that unity 2D extras create for smart tile placement
normaly, u must select tiles that you want in some place
but this will change them automaticly
In your case you can make a rule tile, to make things easier.
Here is a video that explains this pretty good https://www.youtube.com/watch?v=dd4KrKCa3Yg
An in-depth but easy to follow tutorial on how to set up and use the rule tile in your game, starting with an empty project.
My music channel: https://bit.ly/3dFq3Hf
Artist who made the tilemap (Eli): https://bit.ly/376cmyM
#Unity #tutorial #rule_tile
but you must download 2D extras
with the move tool
actually i dont have any idea, i never had to move it 
I have this code, and it worked fine until I added the commented out bit in the raycast script. It then threw me an error, and when i commented it out, it threw me another error that the object was not set to an instance of an object. I have the player variable hooked up in the editor as normal. Whats happening here? I know I dont have any duplicate scripts on my enemy, so this is really wierd
you should probably check if canSeeEnemy is not null first, before getting the collider
it might not have hit anything
nope, did that and I'm still getting an error
whats weird is it worked perfectly 10 minutes ago
I am genuinely very confused
I tried using gameobject.find, same error
looks like the error is coming from the canseeenemy.collider if statement?
Yep, the collider.tag is the part that is being a problem. How do i fix it?
make sure canSeeEnemy.collider is not null. It will be null if the raycast doesn't hit anything
RaycastHit2D itself is never null
but the collider field may be
hello, i was wondering if there was a way to make one sprite loop around?
like if it reaches the edge of a spritemask or something then it starts coming through from the opposite side
Definitely with a custom shader
Possibly with the right tiling settings with a built in shader
probably not as a sprite though, but as a Texture2D
Guys, I have lag problems prefabbing a tilemap grid gameobject. As I understand it, prefab tilemaps are "better editted in prefab mode". BUT I want each of my levels to have its own tilemap (thus editing the base prefab is useless). I need it because the grid is kinda complicated, being made of multiple layers etc.
Anyways, if I make a prefab variant for every level it STILL DOES NOT WORK: It lags the same way as it was lagging on editing the scene's gameobject. So is there another way to make prefab tilemaps to work properly, or I will have to unpack them and make them separately for each scene? (In which case if I need to make a change in all levels I am screwed?)
recently i found that somewhere in the Project Settings is a setting that can allow a 2d object to overlap based on position. But now i cant find it.. anyone remember where or what it was called
you probably want to sort by y. Change y to 1 and z to 0
And sort mode custom axis*
I guess I will unpack my tilemap prefabs. Weird though that unity basically does not allow tilemaps to be prefabed properly
Can somebody help me with a simple but weird problem im having?
what is the problem
can i dm you?
if you want?
sure thenm
hello, I have a raycast script that moves an enemy when a raycast returns true, and a debug raycast that shows me if a line that hits the player happens. When i go into my game, the code sometimes works, but randomly acts like something is blocking it or it stops recognising terrain as blocking it if the object goes far away enough. What's going on?
the script is kinda long so if anyone needs it i'll put it in a pastebin or something
Have you tried logging what object your raycast is hitting?
nope, lemme try that
yep that was it, thanks
tried this line to print out the object:Debug.Log(hit.transform.gameObject);(My raycast is the variable hit), but I get an object reference not set to the instance of an object?
I tried adding a rigidbody 2d to the enemy, now the raycast has stopped working entirely
that means your raycast didn't hit anything
you need to check for that
So Unity physics is driving me up the wall... I found that if I constantly apply torque and add force to a rigidbody 2D, when I enable a collider it will fling the object half way across the screen and rotate it the opposite way... Here is some bad code and the inspector. I am just trying to make a simple version of asteroids but keep finding these bugs.
//script to apply force through a button on screen
void FixedUpdate()
{
//if the player holds the button down we accelerate
if (pointerDown && Player) //If the pointer is pressed and the player is in the scene
{ //Velocity (acceleration)
Vector3 vel = _rb.velocity; //this gets speed of player
if (vel.magnitude < maxSpeed) //if speed under max
{ _rb.AddRelativeForce(Vector2.up * thrustInput * 10); } //increase player speed
}
}
//script on player sprite
void FixedUpdate()
{ //rotation
turnInput = Input.GetAxis("Horizontal"); //arrow keys turning player
float rtn = _rb.angularVelocity; //this gets rotation speed of player
if (rtn < 150.0f || rtn > -150.0f) //if rotation is less than 150 and greater than -150
{ _rb.AddTorque(-turnInput * 10); } //add torque
}
what's the question exactly? And the bug? Consistently applying force in FixedUpdate is the equivalent of strapping a rocket motor to your object. Sounds like the expected result is what's happening
Basically, I am pushing right arrow and it's showing a positive force, but applies a negative force if the player is also accelerating
Until I let go of the the arrow and press it again
can you explain what you meanby "positive" and "negative" force?
player meant to go forwards, player goes backwards
Oh wait, sorry I think I found the problem already 😅
I had a check to limit the acceleration and slow them to a stop if they reached a certain speed, it was badly done
My raycast is colliding with the Enemy object(the script's object) and nothing else? How can i stop this from happening?
Use a layermask
or temprorarily put the Enemy's collider into the Ignore Raycast layer, do the raycast, and put it back
Managed to somehow get it working, but whenever it hits the player, it freaks out with a nullreference exeption and stops the code working that i have in place
As in I barely chaged anything from my original code
NRE will come from you trying to use a method or field from a null reference - i.e "What color is that house?" and you point to an empty lot in the ground.
The thing is, the code sometimes does start working? and the error is thrown only when it detects the player, as it i put the player behind an object it doesnt throw me the error
sounds like you're expecting the player to have a certain component or something that the player doesn't actually have
I'm only using this in the if statement:hit.collider.name == "Player"
and it's name is Playeer
Player sorry
if this gives you a NRE, then your raycast didn't actually hit anything
oh ok
all this raycast crap is hurting my head
would it work if I just added an empty collider under the enemy and checked if that collided with the player?
as a trigger of course
I don't know. No idea what your game is supposed to be doing or what you're trying to do
Oh sorry I may have forgotten about that
I was just trying to see if the enemy could see the player
And stop it from seeing through walls
so the collider wont work crap
Raycasting is so confusing
Imma do it anyway, it'll somewhat work anyway
maybe start by sharing your script and the exact error messages
Seems like some basic syntax errors
oh
oh
that will probably clear up most of them
okay done
still have 23 errors
which are?
start with the top one
line 13
after if start {
what?
Are you sure this is even the same script?
this top
this won't be a cause of an error though
i only made one script
oh k
another error came :/
oh wait
line 14 and 19
you're using ( and )
it should be { and }
ohhh
That's why it's so damn confused
sorry my bad
all errors are gone
tysm
but the script isnt working
i fixed
okay ty
how do you set a variable of a parant object to a variable of a child object?
what are you exactly trying to do ?
you can try referencing the parent varible to the child object via script
nevermind
you fixed it?
Hi, how do I spawn objects randomly only on the x - axis? I'm new to Unity and C#. I currently have this but it doesn't work, any help is appreciated. enem1.transform.position = new Vector2(screenBounds.x * 5, Random.Range(-screenBounds.y, screenBounds.x));
you need to understand the difference between screen space coordinates and world space coordinates. Your enemy's position is a world space coordinate but you are trying to use screen space coordinates to set their position
although you haven't really explained where you're gettin this screenBounds thing from?
impossible to help without seeing the code
can you show those lines the errors are about?
With this code, my raycast works fine while the enemy is not withile los of the player, but as soon as it is, it does not run the code inside the if statement for if its collider.tag is a player one. It should be drawing a green line, but it does literally nothing. When i move it back behind a wall, it returns to normal behavior?
how can get my art that i made in inkscape into my unity project? i want to make a sprite sheet out of my pixel art that i made but there are 0 tutorials that i could find for my situation can anyone here help?
Actually, it seems like it stops raycasting entirely, but only when it sees the player
you're not raycasting properly. Raycast needs a position and a direction, but you'ree giving it two positions
Either change the second parameter to a direction vector, or use Physics2D.LineCast instead which accepts two position parameters
Linecast seems like it would make more sense in this case, in my opinion, but you can make it work with either.
what is the best way to smoothly rotate a 2d object to a certain angle?
Quaternion target1 = Quaternion.Euler(0,0,-60f);
transform.rotation = Quaternion.Lerp(transform.rotation, target1, rotateSpeed);```
i did this and it was more of a snappy movmenet
transform.rotation = Quaternion.RotateTowards(transform.rotation, target2, rotateSpeed);
i used this and it worked, is this a good solution?
t in a Lerp is "time" ranging 0 - 1. If you want smooth movement you need to animate it moving from 0 to 1
alright thanks!
why am i getting a error if i want to know if the velocity of x is 0?
you want myRigidBody.velocity.x == 0
you are assigning ^^
not myRigidBody.velocity.x = 0
ohhh
thank you i thought that was only for if statements
would I need to add a *Time.Deltatime after the
rotateSpeed
well what is rotateSpeed
how fast i was it to rotate currently
float rotateSpeed = 0.7f;
ight
yeah you wanna add a * Time.deltaTime
although you will have to make rotateSpeed bigger
yep that works
i thought that rotate speed was a value between 0-1 only
thanks for the help
np
deltaTime is a very small value. It will split it significantly.
hey, can someone help me with this one? i need to set the position of the firepoint of the weapon to be on certain Y values, i already can recognise which sprite it has, and i have made a public array of vector 3, so then i can put the Y values that should be, but when i code for example
"transform.position = array[index]"
it goes to a completely different one
It returns a different value in the array?
for example
the Y value in the array is 0.5
when it should be 0, 0.5, 0 in the transform
it goes like this
transform.position is the object's world space position, but the numbers you see in the Unity inspector window are actually transform.localPosition
i.e. its position relative to its parent object
How do you put a Texture2D with multiple sprites into a sprite array?
hello simple question
where can i put my out in a 2d raycast?
my line of code
//need to put out topRay somewhere but cant find where
Physics2D.Raycast(transform.position, transform.position + transform.up * rayDist, blockMask);
you don't . 2D raycast doesn't use an out parameter
please check the docs
then how do i get a reference?
from inside the returned struct https://docs.unity3d.com/ScriptReference/RaycastHit2D.html
look at the example code
ok thanks
ok so I got a new problem, how do I prevent the raycast hitting itself?
it keeps on detecting the object the raycast comes from
notice that there is no "source' or "object this came from" parameter. The raycast is not aware of any such concept. TO avoid hitting a certain obejct you can either:
- Put that object on a particular layer and use a layer mask that doesn't hit that layer for your raycast
- Temporarily move your object to the "Ignore Raycast" layer, do the raycast, then set the layer back
ok, thought there would be a function
Actually you can use anything on ContactFilter2D to filter the raycast results: https://docs.unity3d.com/ScriptReference/ContactFilter2D.html
how would i use that?
it's a parameter in the raycast function
ok
ill just go with the changing of layers
wait but will this still work if i have multiple objects doing the same thing?
i have multiple objects with the same script trying to detect each other
yep there not detecting each other properly
it will work because the raycasts happen one by one and the layers will be reverted by the time the next raycast happens
asssuming you revert the layers properly
LayerMask prevLayer = gameObject.layer;
gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
top = Physics2D.Raycast(transform.position, transform.position + transform.up * rayDist, blockMask).transform!= null;
bottom = Physics2D.Raycast(transform.position, transform.position + -transform.up * rayDist, blockMask).transform != null;
right = Physics2D.Raycast(transform.position, transform.position + transform.right * rayDist, blockMask).transform != null;
left = Physics2D.Raycast(transform.position, transform.position + -transform.right * rayDist, blockMask).transform != null;
gameObject.layer = prevLayer;
like this?
yes
weird let me try again
your second raycast parameter is not correct though
transform.position + -transform.up * rayDis``` < why are you incorporating the position into the ray direction parameter?
also what is blockMask?
a mask for all of my blocks?
whatever blockMask is, you're passing it into the "max distance" parameter
so that i can cast a ray in all directions to check adjecent blocks
if you want to apply a layermask to your raycast in 2D, you need to use the ContactFilter2D parameter
this is wrong, direction is just a direction vector
Can someone tell me the best way to save the line shopPanelGO{btnNO].setactive false
I mean between play sessions?
you have to save it to a save file or playerprefs or whatever
so i revamped my code
left = Physics2D.Raycast(transform.position, -transform.right, rayDist, blockMask).transform != null;
so this is good now?
How would I save it to a player pref that was my original idea but it is not a int float or string
yeah
wait but now none of the blocks are detecting each other
PlayerPref isn't really designed for complex data, but you'd have to kludge it into one of those data types
Oh wait this is wrong: LayerMask prevLayer = gameObject.layer;
it should just be int prevLayer = gameObject.layer;
I think the problem is really in my start function. I believe it is because I am setting all panels true
how did you initialize blockMask as well?
wdym?
yea
ok good
nop still doesnt work
show the code now?
void CheckAdjecentBlocks()
{
int prevLayer = gameObject.layer;
gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
top = Physics2D.Raycast(transform.position, transform.up, rayDist, blockMask).transform!= null;
bottom = Physics2D.Raycast(transform.position, -transform.up, rayDist, blockMask).transform != null;
right = Physics2D.Raycast(transform.position, transform.right, rayDist, blockMask).transform != null;
left = Physics2D.Raycast(transform.position, -transform.right, rayDist, blockMask).transform != null;
gameObject.layer = prevLayer;
}
im running it in update
ok and how are you checking if it's working?
the top, bottom, etc are bools
and you're checking them how?
this
what's rayDist set to?
Then it wouldn't work ever right?
.5 only reaches out to the edge of yourself
as a 1x1 block
what if you make rayDist bigger?
ok lemme try
remember the rays are coming from the center of each block
cool
i need to check the blocks so that i could connect them
void OnTriggerEnter2D(Collider2D other)
{
Vector2 bounceVelocityToAdd = new Vector2 (xBounce, 0);
Rigidbody2D itsRigidBody = other.GetComponent<Rigidbody2D>();
itsRigidBody.velocity += bounceVelocityToAdd;
print(itsRigidBody.velocity);
}
When I run this code my player doesnt have the x velocity
however if i change the code and give it y velocity it works
is this a physics related issue?
when i comment out this line it the x velocity works as well
The issue is obvious, isn't it? That line of code is overwriting the x velocity completely
This is the main issue with the "directly setting the velocity" technique.
Using an AddForce technique this wouldn't be an issue.
i see
how would I use itsRigidBody.AddForce() in my situation
myRigidBody.AddForce(new Vector2(5, 0), ForceMode2D.Impulse);
I did this and yet again the x velocity didnt change but the y did when i tried to make it change
Hello guys
Small question
Is there a way to trigger scene changes with like a door??
and how do I save all the state of the player, like health, money, armor etc?
because your other code is still overwriting the x velocity.
this fixed it thanks
Vector2 playerVelocity = new Vector2(myRigidBody.velocity.x + control * speed, myRigidBody.velocity.y);
Even a yes or a no would be fine
however now the playerVelocity is causing the player to accelerate really fast
https://paste.myst.rs/u1beyq49
Cannot read instance id from Json file with Tilemap Tiles information in WebGL. Does webGL not read instance id as these are being saved in json. What's the solution?
a powerful website for storing and sharing text and code snippets. completely free and open source.
does someone know why my player can't jump and moving at the same time?
when i'm moving and jumping it'll first jump then move horizontally while it's still in the air
Like this
Hello everyone ! I'm working on an educational game for kids and one of the stages requires you to draw circles with touch. how can i make the player able to draw using the touch of android and how can i compare what he draw to circles ?
i found a way to draw with linerenderer but the only issue now is how to detect if he drew a circle or not
Have you googled for solutions others have discovered? I think mechanics like this are pretty common
ya i did search on google but but i didnt find much tbh
in some other exercises i need the player to draw lines which should be easy by using a box collider and the last point of the linerenderer but I cant do that for the circles
One solution, is to listen to the touch positions
Calculate a distance from a certain point, then proceed to store those distances within a buffer
If the distances are within a definite limited range
then you could say they've drawn a circle, since a circle is a line of points which are equally distant from a center
For the drawing process you could use a SpriteShape
which allows you to create smooth curved lines
thats genius thnx
Although a shader implementation is possible too
SpriteShape instead of linerenderer ?
If you want to provide the circles with certain visual customization
yes
If you are good with basic coloured lines, it's also okay
I'll look into it thnx again
making the lines look like they are drawn be a crayon would be cuter
Then sprite shape would be the way to go, although it requires spending certain time researching on how to implement exactly what you desire
Good luck with it! 😄
This code(Which deals damage to my player when it collides with an enemy) is Only running once when the enemy collides with my player, and I have to move away and come back to the enemy before it can deal damage again. How can I get this to work constantly while the enemy is colliding with the player?
Nevermind, figured it out
GetButtons may be trying to access some method or field from a null value
Which one is the line 23?
Does anyone know how I can modify a rule tile script to change what it counts as a neighbor?
I want it to count everything on the same tilemap
That's because not all GameObjects with the tag
contain a component 'Button'
thus when you try to access fields relative to the 'Button' class
it fails, because there's a null instead
Sooo. how do I solve it
Make sure all the GameObjects with the tag you've got there, have a Button component
using UnityEngine;
public class Dash : MonoBehaviour
{
public float dashCooldown;
public bool canIDash = true;
public Vector2 savedVelocity;
void Update ()
{
if(dashCooldown > 0)
{
canIDash = false;
dashCooldown -= Time.deltaTime;
}
if(dashCooldown <= 0)
{
canIDash = true;
}
if(Input.GetKeyDown(KeyCode.LeftShift) && canIDash == true)
{
savedVelocity = GetComponent<Rigidbody2D>().velocity;
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x*3f, GetComponent<Rigidbody2D>().velocity.y);
dashCooldown = 2;
}
}
}
why this isnt working
like
there`s no error
it just
doesn`t happen
If you add a debug.log to the keypress check If statement, does it print in console?
i`ll try that out'
The raycast is not doing anything(returning null), even when I put the player on the correct layer(8). Whats going on?
you're shifting your mask in the wrong direction
should be 1 << 8
I recommend simply using a public LayerMask layerMask; variable and configuring it in the inspector instead.
Ah ok now it works
How would i Invert that, so that it looks everywhere but a specific layer?
layerMask = ~layerMask;
This is my new code(with the layermask variable on top, and the in the editor set to my enemies), the debug lines flicker and start/stop working at random, and it doesnt ignore my enemies
well if you're running this in Update, you're inverting the mask every frame 🤔
yep figured that out
putting it in the start method worked
thanks so much for your help!
Is there some way to modify the vertex colors in a sprite mesh?
I guess they don't have the values?
public Button btn;
public Camera mainCamera;
void Start()
{
btn.onClick.AddListener(moveObject);
}
void Update()
{
Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
}
public void moveObject()
{
}
Anyone know how i can use the 'mousePosition' vector3 in the 'moveObject' function
dont declare it inside Update. Declare it outside
declaring it inside Update means it only exists within Update's scope. if you declare it like your Button and your Camera, everything in that class can access it
i need it to be in update tho
no you don't
i said declare it outside. You can assign it in Update
Help! Physics2d.Raycast is not working or something I dunno, I debug the code and every value is 0 or null for the object which is catching value of Raycast... I don't know if this is the problem why my character is not detecting ledges, but it could be
that means your raycast isn't hitting anything
how could it not, character's running on sprite?!
lots of reasons, but most likely you're just passing in the wrong parameters
or the thing you're trying to hit doesn't have a collider
or is in the wrong layer
On fucking point bro, thanks! 👍
Someone have any idea how to fix this. The wall down there is made from two parts, the top one has a sorting layer of 1 and the bottom one a sorting layer 0, the weapon also have a sorting layer of 1. Any ideas would be great
The sword is rotating towards the mouse position
I have a gun object that rotates towards the mouse position. When i fire a bullet, I want to have it face the same direction as the gun. How can I do this?
Let's have a look at the easiest and best way to make top down shooting in Unity!
Check out Jason's courses! https://game.courses/mastery-course-brackeys-bonus/?ref=21
Unite Copenhagen: https://unity.com/event/unite/2019/copenhagen
Armored Soldiers: https://bit.ly/2Zqqn9P
Warped caves: https://bit.ly/2PsOyzS
Tiny RPG Forest pack: https://bit....
