#๐ผ๏ธโ2d-tools
1 messages ยท Page 56 of 1
Anyone know why my player continues to have velocity forever?
Vector2 playerVelocity = new Vector2(control * speed, myRigidBody.velocity.y);
myRigidBody.velocity += playerVelocity * Time.deltaTime;```
Oh wow I am very dumb thanks
float x = Input.GetAxisRaw("Horizontal");
float moveBy = x * 2f;
myRigidBody.velocity = new Vector2(moveBy, myRigidBody.velocity.y);
This works for me idk
that could work yea thanks
Ik this isnt some code stuff but idk where to put it do anyone know a good yt tutorial or something that can help me understand how/to set it up?https://assetstore.unity.com/packages/2d/environments/free-asset-2d-handcrafted-art-117049
look at the sample scene they provide and follow their setup. you're not going to find tutorials for specific assets like this unless the asset author themselves posts one
Is there any rendering rendering or performance difference between placing a regular flat mesh w/ a sprite shader and a using a sprite renderer?
I think the spriterenderer somehow knows how to... use the Sprite asset
e.g. grab the appropriate pixels from the source image (might be a sprite sheet) to feed into the shader
Right, in this case I'm using the SVG library to generate colored sprite meshes.
But the problem is that I don't seem to be able to access the vertex colors for the Sprite instance that it generates.
Aaaaaaah, wait I see. There is a way!!
Does a sprite have vertex colors?
Yeah.
interesting
(I'm looking at the vectorgraphics source)
if (colors != null)
{
var colors32 = colors.Select(c => (Color32)c);
using (var nativeColors = new NativeArray<Color32>(colors32.ToArray(), Allocator.Temp))
sprite.SetVertexAttribute<Color32>(VertexAttribute.Color, nativeColors);
}
Okay... So. My goal is to have a single material for my whole game.
Come to think of it I'd probably better achieve this by modifying uvs and having a palette texture
does someone know if there is a command similar to GameObject.CreatePrimitive but for 2D game objects?
Sprite.Create
ok thanks!
i was looking for it yesterday
i think i'll eventually just create an empty game object and add the components after
well...yes
i find it easier
sorry... ๐ถ
Are ur enemies on a layer?
yes
But they didn't appear even without the layer
I just created the 'Enemy' layer
And is ur main camera having that layer ticked in culling mask
Maybe try setting the z to 0 @faint hollow
What is the background sprite render order layer?
If it's 0 set enemy sprite renderer order layer to 1
๐ try disabling the background gameobject and see if they are visible.
@faint hollow in order to sort sprites in 2d, you can either use the Z axis position (lower value = higher priority), or, preferably, use sorting layers. Are you using one of these methods?
Sorting layers are different from normal layers
Otherwise, it is possible that enemies are just hidden behind the background
so i want to do simple platformer movement , and i have been working for a month taking breaks and trying to figure out how to do it , by now i understood that there are 3 ways of moving the player and none out of wich transform.translate (dosent care about physics) , rb.velocity = sets velocity and overwrites averything else , rb.addforce accelerates and decelerates , none of theese work for me , are there any other ways to do it ? i am a beginner and making my own physics is just not the case at the moment
What you mean none of these work for you? They don't do anything, or you want some specific behavior that these do not cover?
they do function but i am not able to use them for what i need , what i need is for my character to collide with things , and i want my movement to be like , when i press left , character goes left with a constant speed , 5 for example and when i let go to stop in place , no acceleration no deceleration no slide , for this i used rb.velocity = but it ovewrites the velocity , and in my game i will have thigs wich will have to change the players velocity so that wont work for me
addforce feels just janky for movement
and transfor.translate dosent really take physics in consideration and there might be an overwriting problem aswell
it sounds like you just need to set the velocity
you say you need for the character to collide with things, so that narrows it down to physics based movement
you dont want AddForce, so then set the velocity
and work around it. "i will have thigs wich will have to change the players velocity so that wont work for me" doesnt really say why that's a problem
Can you give an example on what else will affect the velocity?
It is possible to add to the current velocity for example. Need more info on what you need
so practicaly i want enemys wich give knockback , spikes , jump pads , and more things that i did not think of yet
this is why setting velocity wont work because it overwrites all the velocity
even if i add to it
Will e.g. knockbacks have a constant speed (no acceleration etc.) And last fixed amounts of seconds? With some additional logic these issues can be overcome
E.g. have a "knockback" timer, which while enabled it adds an additional velocity at this specific frame.
Btw the velocity will probably have to be overwritten on each frame anyways
overwriting is my worst problem right now
E.g.
{velocity = new Vector2 (10,0)}
if(knockedLeft)//determined via a timer or something
{velocity += new Vector2(-5,0)}```
Etc for all things that affect velocity
And the above being under update or fixedUpdate
The velocity will probably need to be overwritten on each frame anyways, depending on the conditions that apply at the specific frame, such as which key is pressed, frames passed after the jump key was pressed(to determine when the player will start falling, if you want to not use gravity) etc
would you mind if i send the code so you can have a look a the way i did it ?
Sure
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerControler : MonoBehaviour
{
public float jumpheight = 5f;
public float speed = 5f ;
private new Vector2 MoveDirection;// private float direction;
private float direction;
private bool isjumping = false; // checks if player is jumping
private bool hasmoved = false; // checks if player has moved
public int health = 3; // hp ammount
public Rigidbody2D rb; // player rigidbody
public Collider2D coll; //
public LayerMask ground; // the ground layer
public Text lives; // ui hp text
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump") && coll.IsTouchingLayers(ground)){ // checks if i am touching ground and have pressed jump button
isjumping = true; // sets isjumping to true
}
}
void FixedUpdate() {
if ( isjumping && coll.IsTouchingLayers(ground) ){ //checks if jump is pressed and touching the ground
rb.velocity = new Vector2 ( rb.velocity.x , jumpheight); // character jumps keeping its current x velocity
isjumping = false ; // sets is jumping to false
}
if (Input.GetAxis("Horizontal") > 0)
{
rb.velocity = new Vector2 ( speed , rb.velocity.y );
direction = -speed ;
}
if (Input.GetAxis("Horizontal") < 0)
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
direction = speed;
}
}
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.tag == "spiketagtest"){
health-- ; // decrements by one
lives.text = health.ToString(); // converts int to ui text
rb.velocity = new Vector2(-direction, jumpheight); // this kinda works , overwriting breaks it
}
}
}
This code(Which is very bad, I'm new to unity) Is meant to shoot three bullets rotated in seperate directions to fire off. However, it seems that they all fire in a single blob instead of off in each direction, though the rotation part seems to be working. What can I do to fix this?
do the bullets collide one with the other ? because if yes that might be the cause
Turns out it was the transform.Right thing
They were firing at the same area
My bullets are also triggers
Got it to work
@still tendon when there is knockback, you could have a counter of e.g. 50 frames where input won't work and knockback velocity will be refreshed.
so you mean to put the move on a condition like if not damaged i am allowed to move ?
is there anything like a timer function or ?
hiyaa how would i make camera bounds for my 2d top down game so as in when the player walks to far left the camera stops following them
I'm very new to programming and idk how to fix this
my "player" doesn't jump
If you are using physics then you need to use .AddForce() instead
And move that logic to FixedUpdate(), Update should be for registering input only
You can just use a variable such as "int maxFramesDamaged= 50" and then a counter "int counter = 0" And for each update you do
FixedUpdate(){
counter++;
if(counter<maxFramesDamaged){
//do stuff e.g. knockback
}}
and you reset counter to 0 whenever you are damaged
That is what I use to have control over how many frames (fixedUpdate frames) some effect lasts. There is also a way to do something for a specific time period in seconds, which is more or less identical considering that FixedUpdate runs 50 times per second at default (which means it is also translated into time). I personally prefer doing it with the counter thing though
The second way that I was mentioning is coroutines
uhh i'm not sure where to put the .AddForce()
The Input.GetAxis value does not instantly jump from 0 to 1. Just for clarity, can you try to keep the jump button (up arrow) pressed for a couple of seconds to see if the player jumps?
@elder citrus
doesn't work 
wait, you initialize "jumping" as true
It needs to be false, and also some way to return to false after the jump is completed
alr so i replaced the true with false and now the jump works if i hold down the up arrow for a second
use Input.GetAxisRaw to jump immediately
Basically Input.GetAxis gradually moves from 0 to 1 (or from 0 to -1) which is sometimes desirable for gradual acceleration. Input.GetAxisRaw goes instantly from 0 to 1 or -1
Input.GetAxisRaw makes the square slide really far when i release
Alright thanks it works fine now
Alright i have another problem lmao
when i hold down my jump key, the player just flies up as long as i hold the key
i have searched for solutions on google, on youtube and none of them worked
Where do you set the jumping variable as false?
maybe i'll just redo the whole thing with a tutorial
Hi, I'm trying to create a 2D multiplayer game where each player draws a card and then drop it in their respective slots. when both players drop their cards in slot, the player with highest card value should get a pop up text as winner. Now as you can see in that video, i've managed till the part where they can drop each of their cards in their slot. How can i make the game declare the winner with highest value?
Wouldn't that greatly depend on the way you coded this?
Where are you storing the cards' values? You need to compare them
https://paste.ofcode.org/35fYT6GZpgGQuFvYWscPYte here is my playermanager script
I've not stored card values yet. I've four sprite card images as gameobjects
Well, where do you plan on storing the values? Where exactly are you stuck?
i'm a beginner , so i dont know how to proceed further,
How did you do this code so far? Did you take the code from somewhere?
as you can see in playermanager random sprite images get assigned to each player and when they drop it in the slot it flips
yes a tutorial video but i'm trying to implement my own logic where th player with highest card value wins
when both players drop their cards in slot, i should compare the values and post the winner
You'll need to have the cards data; stored somewhere - a variable.
How do they know they've got a card?
like in the above video, it gets displayed in their playarea
I cannot watch videos on this network. Who's managing the cards?
playermanagerScript
I'm assuming both players have multiple cards so they manage these cards somewhere.
So when you drop the card, you've selected your card and once both players have selected their cards, you simply compare the selected cards values.
if (p1.selectedCard.value > p2.selectedCard.value)
p1 win
else if (p1.selectedCard.value < p2.selectedCard.value)
p2 win
else
draw
@vocal condor my card is a game object, i have put it in a list to randomly assign a card to each player. how to assign value to the cards?
I tried this but I get an error " cannot implicitly convert type int to gameobject
@still tendon I suggest watching the Unity Learn tutorials under the pinned messages of #๐ปโcode-beginner. If it were me, I'd make a new script called Card and give a public field value then add that component to the card game objects.
hey i have planned to create sepereate scripts for each card where i will put their value
and then in playermanager im planning to compare by getcomponent method!
In your player manager, I'd reference the cards as type Card (still a Game Object but you'd have access to the component Card and it's members as well).
Then you'd be able to check the cards value: card1.value.
seem familiar, killgrave? I did suggest you make a Card class last time too
and it doesnt have to be for each card. they all can have the same Card class, just assigned different values
Card1.GetComponent<Card>().ValueToSet = yourvalue;
You probably don't want a separate script for each but rather a single script and multiple instances (a component on a Game Object would be consideredr a different instance).
wow thats really helpful thank you guys
hi, please tell me where and how to put that code in my playermanager https://paste.ofcode.org/srdcSKk3L66VasDpbWPSAg . how can i get the selected card ?
Do you have the selected card? (Game Object according to you)
the sprite of the card will display in the playerslot1
Well, you could set the cards value based on sprite name then.
Where no sprite equal 0 value
And not ready
Card1.GetComponent<CardValues>().valueToSet = value1;
Card2.GetComponent<CardValues>().valueToSet = value2;
Card3.GetComponent<CardValues>().valueToSet = value3;
Card4.GetComponent<CardValues>().valueToSet = value4;
did this to assign values to each card!
You could just reference the cards as type CardValue to avoid the get component calls.
So instead of public GameObject Card1 it'd be public CardValues Card1
okay I will try that
So I am very new to coding just started and I want the script to follow the player but it just shows this
wait should I ask that in beginner code?
I fixed it nvm
sry
lol
@shadow flint Z position on the camera needs an offset
I fixed it with "transform.position = new Vector3(target.transform.position.x, target.transform.position.y, transform.position.z);" I saw one of the comments say it
I have this code to check which direction the player is facing and to face the mouse. I want it so that the direction is clamped to only be able to rotate it so that it can only rotate on the right side(so it cant rotate to the left), and same thing for left. My brain is way to smooth to be able to comprehend how to do this.
Use Vector2.SighedAngle to get local rotation to the point then animate the rotation.
how would you write that In code? I'm not really familiar with that function and the docs dont have any examples
If you don't understand something start experimenting with it. It's pretty straightforward.
Is there a better way to handle movement for a Rigidbody2D that would allow for knockback? Right now i'm setting the velocity directly because that gives the best feeling movement out of the methods i try, and then if a knockback happens i disable controls, apply the knockback force as an impulse, then re-enable controls. I've tried MovePosition but that ignores velocity entirely so i'd be doing the same thing anyway, and using addforce for movement feels too slide-y.
Kind of hacky but perhaps```cs
public Vector3 next, previous;
//...
rb.velocity -= previous;//Undo previous velocity change from movement
rb.velocity += next;//Add next velocity change from movement
previous = next;//Update previous to next
hi im looking at drawing tiles on the screen using the diamond square algorithm. im at the first stage. i kind of understand the algorithm but am having trouble connecting the dots of actually rendering them to 2d tiles. can anyone point me in the right direction? ive spent the last few days on google
@vague meadow how are you trying to render them? To a texture? Tile map? 3d geometry?
i want to render the height map first then render it to a 2d tilemap ๐
Hey I'm trying to make it so I can drag a UI panel vertically up to a certain point on the screen, and it can go off the screen to about 50% of its height
moving here from beginner code because there were no replies and its a bit busy
When I start the game, the UI panel immediately disappears
Sort of like this
So that you are still able to grab the panel when it is at its minimum position (a little overlapping the screen).
Actually I may have a solution I'll have to try it out :)
@vague meadow I don't know enough about writing to an image in Unity but as for the pixels of the heightmap, isn't that what the weights of the diamond square algorithm are for? Each pixel is colored based on either every center point in the grid being a pixel, or gradients between the points based on the width of a single grid cell.
@split flame yep i get that part the algorithm makes sense, im just coming from using 2d tile editor to wanting to generate one procedurally but cant find where to code that from heightmap to generated tilemap and render to screen! how do you guys figure this stuff out ๐ณ
lol, google and trial and error.
have been on there for the last 3 days, heads still spinnin'
documentation is either old or its missing the step i need x)
You would make your heightmap grid, then choose tiles from your tilemap based on point weight, I guess.
some of those threads be like from 2010
yea i did search for probably 24 hours now and thought i'd try asking around because the searches didn't get me there (i must be dumb or smth gotdamnit)
Are you placing tiles from a premade tilemap?
i was using the basic editor but that means i have to hand craft everything, at least that was never my final intention, i wanted to move to this but now im trying to wrap my head around it before i do it to a tree instead
Or are you trying to split the generated heightmap into tiles and make it a tilemap?
so yea the very first steps im trying to find the right entry point to see it on my screen. the basics of, a, apply diamond square to an array, b, create pixels or tiles (either or) based on height, c, display to screen
ah, look up how to draw to a texture in unity
what about drawing a map out of pixels that represent tiles
so basically the heightmap but rendered
so yea what you're saying through that, then the last step of making it into tiles
sorry man, im lost dont mind me
but i am continuing to search anyway, my googlefu is strong, i need to find morpheus first
I'm not entirely certain this algorithm is what you are wanting.
The heightmap is intended to be used to generate terrain recursively to get detail
im more wanting the ability to understand and comprehend this stuff, regardless of chosen generation of map, to create maps and generate them into 2d maps
So you can have an arbitrarily detailed heightmap
No problem, it's important to challenge yourself.
it is an area i have to explore, but u may be right
im also looking into perlin and simplex
anything but white noise
This isn't really the best algorithm for making 2d tiles.
diamond square seems to work fine but what do u suggest sir
just based on what ive seen
more 3d or fake 3d tiles
the 2d implementation shouldn't be insane
i just want to generate heightmap and display it on screen either as pixels or those pixels represented as tiles
ive put it out there now ahaha im going back to google but thanks for ur time dude
if you want to display it, then create a plane and a texture, set the texture to the material of the plane, draw on the texture based on your heightmap
no problem
guys, in my game i have to declare the winner text when both player and opponent place their card , but my winner text appears immideately after the player puts his card on slot because opponent card value is 0 by default. how can i fix this?
https://paste.ofcode.org/GaRUFJ7E4YyCM4RxpWk6Ca my gamemanager script
use a boolean to check when both players have put down their card
2 booleans, if necessary, like isPlayerCardDown, and isOpponentCardDown
or, just check if both card values are more than 0
okay i will try that
Like in the video the code is working perfectly but the texts appear before handed , I want it to appear after both place their cards. Please help
did you try any of the suggestions I gave?
you really need to learn the basics @still tendon
different scripts are not a problem. You get a reference to variables in other scripts by getting a reference to the gameobject that has the component
instead of actually trying the solution and asking about it, you decide to just ask the same question without changing anything. it's not the first time you've done this
@turbid heart thank you so much i tried when both values are more than zero and it worked . thank you ๐
@turbid heart , the text stays back even when I end the game how can i get it disappear?
do the opposite of what you did to show it
ive been going trough the internet for awhile now and i cant find anything that would put an object in a 2D project to always go to mouse position
so any help for this
can you elaborate on this? do you mean you want the object to be at the mouse position all the time?
well, first you need to understand that mouse position is using screen coordinates. your objects in your game are using world coordinates
yeah
you need to find a way to convert Vector3s from Screen to World coordinates, and vice versa. Hint: There are methods for that under Camera
Hello, I'm trying to lock the rotation of the object this code is attached to so that it can only rotate on the right side of itseft when facing right is true and on the left side when it's false. I was told to use vector2.signedangle, but a google search on the docs and in unity answers didn't give me much info. How would i go about doing this?
I think the code you're looking for is camera.screentoworldpoint, the docs for it are here:https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
thanks
np
What kind of object are you rotating using this code? Does it have a sprite attached for example?
That's the gameobject's inspector thingie, its for now just a regtangle that I use to shoot bullets out of
It also has child objects for its barrel(where the bullets come out of) and its a child of the main player so that it moves with the player
for now it just faces the mouse
Am I correct in assuming that this is your desired behavior?
The white line indicates the mouse position. The blue circle indicates the facing direction. The red bar is the gun.
I managed to find a solution to the problem, turns out another method worked well enough. Thanks for your help tho
This is my movement code(on an object with a dynamic rigidbody, so it can be effected by gravity). It works pretty well, but whenever I walk into a wall on the x axis, it does a glitchy thing where it moves the player out of the wall. How can I just get it to stop when it collides with a wall?
transform.position = position;
This line of code is breaking things
you're bypassing the physics engine entirely with that line, which is why you're tunneling partially into the wall
you need to move your Rigidbody via setting its velocity, adding force, or calling MovePosition() on it
How would I do that in my case, Ideally without adding too many new lines
tried this code:
float x = Input.GetAxisRaw("Horizontal");
float moveBy = x * 10 * Time.deltaTime;
ownrigidbody.velocity = new Vector2(moveBy, ownrigidbody.velocity.y);
but it didnt do anything?
nevermind it was stuff in my code
This script is handling my jumps. When it's doubleJumping, sometimes it just doesnt add to jumpamount variable at all, and sometimes it does. I know the code is running the doublejump part because of the debug.Log at the end. I am very confused. This is the only part of my script that handles the variable of jumpamount, so it can't be coming from there
Is this in FixedUpdate?
its in regular update
all i can say is step through the code line by line (ideally in the debugger, but use log statements if you're not familiar with it) and see what's going wrong
there's a lot of conditions on that if statement
any of them could be false
also there's the jumpamount = 0 bit that could be happening too
Putting it in fixedUpdate seemed to work
Someone have an idea how to make sideways movement, but when I hit a obstacle, or a wall the players keeps walking left or right. For example if I hold down and right button at the same time, I go sideways but when I hit a wall I want the player to continue going right but slower of course.
You get this for free pretty much if you use physics-based movement
I am using MovePosition. Is that it?
Like this
@snow willow Do I need to change some setting in Unity?
nah you'll want to actually use forces to get what you want
yes
Okay gonna check it out, thank you
I'm following this tutorial, trying to programatically generate meshes and colliders for a 2d game(like terraria) but even after copy pasting the same code my player just goes through the generated squares(i tested with box collider and it works) http://studentgamedev.blogspot.com/2013/08/VoxelTutP2.html
any help would be appreciated
How can I detect when a rotating object collides with a wall? And with a wall I mean not the ground below it, but anything that is higher than the floor
Basically I have this guy in the middle and I only want to detect when it collides with the red things, but not with the blue things, no matter what gameobjects the things are from
My inventory isnt being found? Why?
using System.Collections.Generic;
using UnityEngine;
public class InventoryUI : MonoBehaviour
{
Inventory inventory;
// Start is called before the first frame update
void Start()
{
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
}
// Update is called once per frame
void Update()
{
}
void UpdateUI ()
{
Debug.Log("UPDATING UI");
}
}
I put the script on my Canvas like Brackeys did in his tutorial
well wheres the inventory script lol
also what do you mean by its not being found?
i dont have a inventory script yet
lol
:O
IM SUCH AN IDIOT
i might have missed an episode of the tutorial im following
Yes
how do I use the onPointerEnter thing without getting an error underneath it?
you should say what the error is when you ask these kinds of questions, it would make it easier to help you
Didnt think about that before posting, did not phrase my question right at all, sorry. I'm trying to check if the mouse is hovered over a button and then to change a variable if thats true, Through some googling I found onpointerenter as a component, how can I acess that inside a script?
Like if its hovered over then run a specific function
You use it like in the example here https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Selectable.OnPointerEnter.html
Does anyone know this?
Use layers
But what if the red and blue thing is the same game object?
Is there a different way? I want the system to be dynamic and it wouldnt be if I had to assign a layer to each game object based on their position to the enemy
I could also make a seperate game object that has two trigger colliders and a position constraint so that it follows the enemy but that doesnt seem like a good way
That works
@dusky wagon so you want it to collide with only vertical colliders?
No, the shap doesnt matter. I have a rolling object that rolls around in the floor in one direction, until it hits something. Then it changes the direction
But I only want to detect if it collides with something that isnt the floor it is rolling on
Im also going to try this in a second to see if that does what I imagine it will do
Or well depends on what vertical colliders means
Vertical means up-down
Okay yeah thats what I thought
How do you expect to differentiate "floor" with other colliders? There must be something you can compare
I wanted to do this, so that there is a collider to the left and right of the object that can only hit walks
You need all colliders (both floor and walls) to belong to the same game object?
Yeah they can be from the same object but they also can be form different ones
If they can be from different ones, what is the problem on making a separate "floor" collider, and then assigning it a layer?
You can then very easily tell Unity to ignore interaction between "player" and "floor"
Well because I want a collider to count as a floor for one object but maybe count as a wall for another one
You can tell Unity to ignore interaction between "player" and "floor", but keep interaction between other layers
that's the basic premise of using layers. You can choose which layers colliders interact with each other and which dont
But it would be really tedious to assign a different layer to each platform and make each of the enemies change their layer based on their position
make each of the enemies change their layer based on their position what do you mean? What exactly is the gameplay on this aspect? Do some colliders have to change this specific behavior?
will e.g. an enemy sometimes ignore the floor, but other times collide with it?
Wait Im probably not being clear enough with my question here let me try to re ask it
So I have this setup for example. The grey square is a tilemap that has a tilemap collider. At the top I have the enemy. I want that enemy to get left until it hits a wall (marked red in this example). As soon as it hits that wall it switches the direction and goes right until it hits somthing. Since in this case there is nothing in the way to stop it it will fall down into the pit. In there it will go right until it hits the right wall that is marked red. As soon as it does that it will switch direction again
I hope that is a bit clearer
But I want the whole system to be dynamic, so that I dont have to mark every single edge part
so the floor will also be an interactable collider since the enemy will not fall through it
You can add two triggers on the enemy, one on the left and one on the right. Then check in OnTriggerEnter() which one triggered, and adjust accordingly
Of course this isnt the actual game, its just a visulization I drew in 30 seconds
makes sense
[SpriteShape, Spline] Currently trying to dynamically create a visualisation of a Rope composed by a bunch of, tiny 2d box colliders. The problem is that due to the nature of the problem, these boxes are close together, so Spline throws up exceptions due to the control points being too close to each other. Thus, I've decided to force a certain minimal distance between these control points, but it keeps throwing exceptions although the distance is much bigger than the minimum defined by Spline: 0.01f. Anyone had a similar experience with spline and SpriteShape? Have you managed to solve the exception throwing in a logical manner? The code for forcing the minimal distance is the following one, and is working correctly, but it seems somehow Spline keeps complaining about it: ```private void SafeSequentialInsertPointIntoSpline(int index, Vector3 position)
{
if (index < _spriteShapeController.spline.GetPointCount() - 1)
{
throw new InvalidOperationException("Point is not being inserted sequentially.");
}
Vector3 previousPoint;
if (index > 0)
{
previousPoint = _spriteShapeController.spline.GetPosition(index - 1);
float squaredDistance = Vector3.SqrMagnitude(previousPoint - position);
if (squaredDistance < MinimalSafeDistanceBetweenPoints * MinimalSafeDistanceBetweenPoints)
{
Vector3 direction = position - previousPoint;
position += MinimalSafeDistanceBetweenPoints * direction.normalized;
}
}
_spriteShapeController.spline.InsertPointAt(index, position);
}```
o-o
Yep
fun fact: his name is "Simple"
Yeah this is the thing Im trying right now, but since the object is rotation, I have to make a seperate game object that has a position constraint so that it follows the enemy and attach the colliders to that and I wasnt sure if that is a good way to do it
mmh
That's an okay way to do it. You could also make the rotating part a child of another gameobject
Why don't you create two game object with a trigger and put them on the sides?
I didn't really got the question ,_,
On what sides?
on the red sides
so that when it touch those it changes direction
And how exactly would that work?
The parent object wouldnt follow the child one right?
How does your rotation works?
No the other way around, you can split graphics and "enemy". So you would have a hierarchy like:
Enemy
- Graphics
- ColliderLeft
- ColliderRight
(as an example only)
Currently its just a rigidbody that is move with velocity and doesnt have a frozen rotation
Hm that could work, but I probably have to use a different method for the rotating then right?
I would make an animation for that
when it touches, it triggers and the animation speed goes -1
You shouldn't have to, but I don't know your exact setup either
My current setup is just an Enemy object that is rotated through a rigidbody
But with this setup the rigidbody would have to be on the enemy
Does the "rotating" actually have gameplay impact or is it purely visual?
Purely visual
why don't you make an animation?
Because it would be a lot of frame and I am not too familiar with the recording animation timeline of unity
I'd just rotate it in script since the animation is that basic.
graphicsObject.transform.Rotate(0, 0, Speed * Time.deltaTime);
Yeah that was what I meant with a different method for rotation
Gotcha, then yeah the way I suggested would work in your situation
Just a general tip always when doing games is to separate visuals from gameplay logic, it usually helps a lot. Obviously on static objects they can be on the same object.
Also one more thing, how can I make it so an object cant be pushed by other objects in the scene? Im guessing one of the three modes for rigidbodies, but none of them work for me
Mark the rigidbody as kinematic, they can only be moved in code. Or do you mean from a specific object?
yeah
I want the object to also have gravity
so it moves but can't be pushed?
Yes exactly
what about something like that OnCollisionEnter it freezes the position and OnCollisionExit it unfreezes?
But then you could stand on it and it floats
Like when the object is mid air and you stand on it it would float
ohh like a flying platform?
Well thats exactly what I want to avoid
Is it maybe doable with layers?
in settings > physics i think there's the physics collision matrix where you can control which layers interact with each other, but that would mean they completely wouldn't interact with each other so they'd phase through
if you set rigidbody to kinematic then it can't move unless you program it to
so you could add some gravity through code by doing addforce to move it downwards
I have the weirdest issue ever right now, this is the first time it happens in any of my projects but my tilemap isn't exactly horizontal with the grid
When my player moves on the grid horizontaly his Y position decreases if I go left (by like 0.0001 per pixel) but it's enough to mess with my falling check etc..
Yeah thats probably what I have to do. Is there an easy way of making gravity without too much complicated math?
you can do an addforce every frame of vector2.down * gravitySpeed
every fixedupdate
Okay I will try that
Oh and is there a good way of detecting when it leaves the ground? I obviously cant be constantly adding force to it even if it is on the ground
I have made idle side and front animations, so when you stop walking you go to the correct idle animation, but sometimes it glitches and flashes the front idle animation b4 going to the correct idle animation. How can i stop this. Ping me if you reply. Thanks.
It seems that the problem arrived from the logic of Spline's point validation, since it always checks the distance between a point and the origin point of the spline, thus, requiring the safe method to assure the distance, between the points and the origin, is greater than the minimum. The final result is this one: ```private void SafeSequentialInsertPointIntoSpline(int index, Vector3 position)
{
if (index < _spriteShapeController.spline.GetPointCount() - 1)
{
throw new InvalidOperationException("Point is not being inserted sequentially.");
}
if (index > 0)
{
Vector3 previousPoint = _spriteShapeController.spline.GetPosition(index - 1);
// Check distance with the start of the spline, due to the position validating logic of Spline.
Vector3 originPoint = _spriteShapeController.spline.GetPosition(0);
float squaredDistanceFromPreviousPoint = Vector3.SqrMagnitude(previousPoint - position);
float squaredDistanceFromOriginPoint = Vector3.SqrMagnitude(originPoint - position);
Vector3 safeDirection = (position - originPoint).normalized + (position - previousPoint).normalized;
if (squaredDistanceFromPreviousPoint <
MinimalSafeDistanceBetweenPoints * MinimalSafeDistanceBetweenPoints
|| squaredDistanceFromOriginPoint <
MinimalSafeDistanceBetweenPoints * MinimalSafeDistanceBetweenPoints)
{
position += MinimalSafeDistanceBetweenPoints * safeDirection.normalized;
}
}
_spriteShapeController.spline.InsertPointAt(index, position);
}```
I added 3 buttons in a Canvas 2 of them works when i click them but 1 doesnt can someone help?
The render mode of the canvas is Screen Space - Camera
Doesn't sound like a code question, try #๐ปโunity-talk
so i currently have a portal script for when the player collides with it it loads a new scene that i can either manually specify (or randomly if i do endless dungeon or something) but is there a way to make a spawn point i can add to each scene? because i am doing it similar to pokemon in a way. player starts in center of their room after creating character, but for other scenes i may want them to start at bottom of the map and stuff. or do i just have to build the maps based on where i have my character placed in my creation screen (as i have the player prefab on do not destroy so it just carries over to scenes
You can teleport the player to a specified position when you load a scene, however you would probably want to disable its collision and controls until it is teleported to prevent issues with its position at the start of the scene
Just set its transform.position to the preferred 'spawn' point
thank you, i think i have something working
hi, is there some way to specify the centerpoint of an image?
I think you specify it in the sprite importer
pivot settings are in there somewhere
Hi! Im new with programming with unity. I installed Cinemachine, URP, Pixel Perfect. When I hit play, my Cinemachine camera is flickering and the size is changing.
And I installed the new Input System and now i get this error: ```InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.EventSystems.BaseInput.GetButtonDown (System.String buttonName) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/InputModules/BaseInput.cs:126)
UnityEngine.EventSystems.StandaloneInputModule.ShouldActivateModule () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/InputModules/StandaloneInputModule.cs:227)
UnityEngine.EventSystems.EventSystem.Update () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:474)
How can you delete tiles from a tilemap through code?
TileMap tilemap = GetComponent<TileMap> ();
tilemap.SetTile(new Vector3Int(0,0,0), null); // Remove tile at 0,0,0
Thanks!
Do Anyone know why?
u should rather stop trying to use the new input system until it's done
i found the error ๐
cool cool
Hey! so i have a code for making a grid, however it gives me this error:
NullReferenceException: Object reference not set to an instance of an object
GridManager.GenerateGrid() (at Assets/Scripts/GridManager.cs:33)
this is code of the function: https://pastebin.com/4NVeXDtn
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.
line 33 is ```csharp
_tiles[new Vector2(x,y)] = spawnedTile;
what is _tiles and why are you indexing into it using a vector2 ๐ค
should probably be on the safe side and make your grid using Vector2Int as the key
instead of Vector2
(not really related to your issue)
oh i forgot XD sry now it works
Is it possible to have a serialisfleild string variable with a limited amount of options in the inspector, IE a dropdown?
google it
im not sure but u will probably find it if u google
You could probably use an enum instead
figured it out via google
so , since i started learning unity and all , i learned that physics are a big no when it comes to platformers , and i learned that i should move my character via script , so i started making my movement using transform . translate , but another has risen , i need to create the colissions manualy thing i do not know how to do , i searched rough tutorials , reddit , unity manual and all to se how i could do hat , and i did not fiind anythings usefull , or something that i would understand , so i thought i might ask overhere is anybody had to deal with this and if yes how i could aproach it , i must make my own character movement because i want it to have some variety with it so just using a premade cc wont work for me
There's nothing wrong with using physics. I'm not even sure what you're asking here, are you trying to create a game or physics engine?
i am trying to make a platformer game and for it i need to make my own movement withous using unitys physics engine because its just bad for this kind of stuff , what i am asking is if anybody on this server had to deal with this and if yes id like to ask them ways i could aproach creating collisions
I think you have some weird assumption about unity physics. Just do you movement using raycasts. If you want to "Create own collisions" then you should start studying a 5 year Computer Engineering course at your nearest University. I really like this channel for this sort of 2D movement stuff: https://www.youtube.com/watch?v=MbWK8bCAU2w&list=PLFt_AvWsXl0f0hqURlhyIoAabKPgRsqjz
its not just assumptions , its what i have experienced for myself together with lots and lots of people who said the physics engine is just not good for 2d platformers
Well then your only option is to study at university and then write your own game engine, or switch to some other engine.
Basically what I'm saying is that if you can't say exactly what's wrong then there's no reason for you to keep assuming something is wrong.
but i know what is wrong , im not asuming thats what im trying to tell you , and this is the reason i must make my own physics for my game
Then tell me
using unitys physics engine for my character means that i must use a rigidbody for it , the problem of the rigidbody are the ways it can be moved those that i know beeing rb.velocity= ; rb.velocity += , rb.addforce = , theese ways of moving the character are bad for what i need for the following reasons those beeing code overwriting ,inconsistency , sliding , acceleration , deceleration , and other problems that ive had trying to fix them that i cant think of at the moment , reasons for wich i must move my character via script and not via forces , ive tryed fixing those problems many times in fact i lost at least a month on that , asking , reading following tutorials and overall learning with next to no progress , and moving the character via script also means that it totally ignores the rigidbodys collisions for wich it means i need to make my own player movement / physics / character controller
Follow the tutorial I linked and trust me, you do not want to write your own physics system
the reason i need to make my own character controler is because with that i can make my movement thw way i want it without those problems
You can use the Unity physics system and then do movement as explained in the tutorial I provided
by physics i mainly mean collisions , grvity and movement in this case
U gonna use character controller?
i dont thick unitys physics engine is bad is just that its not good for this kind of stuff
It is good for that kind of stuff. You are just inexperienced
Look at games already made with it, like Ori and the will of the Wisps, they're prefectly fine.
DONT
not going to use the character controller , im trying to make my own to fit my needs
Hmm
Then ok
Good journey my friend
Come back with victory
๐ฅ
ill try ๐ even if i fail at least ill learn something
Check the tutorial I linked earlier, it's VERY good
Yaya
NEVA GIVE UP - https://bit.ly/2VrgAcK
Song is Before my Body is Dry instrumental version from the anime Kill La Kill
Consider donating to our Patreon!
https://www.patreon.com/psycosmos
CASHAPP: $TeamPsycosmos
Check out the Psycosmos OFFICIAL DISCORD!
https://discord.gg/EAJkY3V
Make sure to follow us on Social Media and support us!
Instagram...
If you fail watch this
๐๐๐
Dudes typing a whole novel

i checked it few times and it is a good tutorial havent finished it yet but its hard for me to understand of lot of the things he explains , a lot of those things he uses dont make sense for me taking in consideration the fact that i need to translate wha he says into my language and a lot of those commands come out of nowhere and i simply dont understand most of it
trying to do , i google search new commands he uses , their purpose and other
Is there a good way of detecting when an object is getting crushed before any glitches happen?
anyone know an easy way to access a gameobject that is inside of an overlap circle? please @ me
@dreamy fractal you can make an array of colliders and set them to be the return value of the overlap circle function and then kust do a foreach loop to go through each element
ok, thanks
howdy folks, think this might be the home for me for a while
well here and the beginner code channel
do we have any pros here?
ah i see
how do I have my raw image only be visible inside a sprite mask?
Does isometric count as 2d ๐
No, it refers to the perspective of the game.
In a 2D game, that is faked by using isometric sprites. In a 3D game, it's simply by rotating the camera so it's at an isometric angle, usually with an orthographic camera.
So if I had a 2d game with a cam set up at an isometric angle, thatd be a dumb thing and probably cause issues?
Depends. If you go true 2D, then the camera is going to be flat angled, orthographic and you'll need to use isometric sprites.
Or you can use a 3D camera, set up isometrically and use 2D sprites in a 3D scene.
Yeah that's what I need to do i think, I had a orthographic cam with 3d models and it was all going fine untill I tried to make an aiming system it just wouldn't work
Time to scrap and start over
There are many ways to abstract aim.
I think the way I made would be better fit for a 3d cam
Gonna try
Can I like just Change my unity project/cam settings from 2d to 3d or will I have to make another project
There isn't any significant difference between the two. Only when you use specific shaders and 2d lighting
...so are you going to ask your question?
How can you detect when an objects collider is being crushed by two other colliders, before it gets glitchy?
I have a player and an enemy, and Both have dynamic rigidbodies so they are effected by collisions and gravity. However, my main problem is that they can push each other around. How can I stop this from happening without excessive use of code or by changing the rigidbody type?
Did you want them to ignore each other completely, like no physics interaction?
no, I still need them to be effected by terrain and other things I might need them to collide with, and I still want to be able to check for collisions between them, I just don't want them to be able to exert force on one another
Ideally no, I don't want them walking into each other
I need to be able to use oncollisionenter for my damage system
Avoid collision with each other using https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
That would make them phase through each other entirely though?
I guess that would work
Ok got a statisfactory solution to that problem by having a second trigger that stops the enemies moving, thanks for your help!
Does anyone know how I could do that?
Perhaps cache collision targets per frame. If it exceeds one (meaning you may be in a pinch) evaluate if they are giving you enough space.
How exactly do I do that? How do I evaluate if it has enough space?
Hm but I would probably have to check from which direction the two collisions are coming from which Im not sure how to do, since the ground is a tilemap so I cant just check the position
๐คทโโ๏ธ Should just be able to raycast towards the other and use the hit distance; after you've determined that you're in a pinch. There are too many ways to do this. I recommend brainstorming and committing on something you can do.
Alright thanks I will do that
How would you check if an object is completely inside another one, for example a tilemap collider?
very dumb issue here
I've tried a few things but I just can't get how to change the alpha of an object so that it fades out?
https://hastebin.com/jixiyowexe.go here's what I've done so far
chances are maybe it's better not to use getcomponent and that's what's ruining everything, but idk
you shouldnt use exact equality like == when it comes to float. Floats are imprecise
use >= instead
also it would have helped if you described what the issue actually is, and to show where that code is actually run. I'm assuming right now it's in Update
yeah, update
but I mean, I'm just trying to make two images fade out
and go transparent gradually
well, what's happening now?
have you debug logged to make sure that code runs?
I think I have?
but even then, it should?
I'm going to
even then though, I really do expect it to
well, kill me
seems like it didn't even run in the first place?
that is so dumb and embarrassing
yeah, that's what you should usually check first when debugging
how bout showing the full update code?
but really, knowing my luck it's not going to work when I actually get it to run
double oof, found out why it doesn't run too
or not, still not running
but even then, we see this is clearly the issue
going to shut up if it runs and it works
oh, so it does run?
it didn't say the message because I put it at the end
so something inside there is ruining everything
going to try and put my debug message further and further to see the culprit
that was... not even necessary? Just realised it sends an error too
well, here's the error now
oh, it has no spriterenderer
uhm, is that meant to be only accessible with a GameObject?
this is an image, so I can't just getcomponent<SpriteRenderer> with it?
oh, heck
well then
hmm
I've changed it and sure, no more exception, but it really still doesn't change the alpha
wait, it did? Typed too early I guess
Now I'm going to try to actually be patient
so it just kept waiting a long time before doing it
that's because I set it to 255f earlier on
well then
well, it works now
It's things like these that make you wonder why I have the programmer role
thanks anyways...
alpha goes from 0 to 1
yeah
before maybe I was considering like, the color there
the other color
idk how to explain that
maybe you got it
this is why you should just provide the full script next time. better context
you'll do better next time. You learn best from mistakes, and you pretty much figured it out yourself. don't give up
to be fair there were some other things that I needed transparency for so this incident was somewhat of a scripted event
Hey i'm not sure if this is the right place to ask this, but I'm a beginner to Unity and to C#. I'm trying to make a script that has the camera follow the player. My script is here, but I'm getting an error saying that GameObject doesn't define position.
public class CameraMovement : MonoBehaviour
{
GameObject Player;
void Update()
{
transform.position = new Vector2(Player.position.x,Player.position.y);
}
}
I found this next one online, but I just got a blank screen when I ran it ```
using UnityEngine;
public class CameraMovement : MonoBehavior
{
public Transform player;
void Update ()
{
transform.position = new Vector2(player.position.x,player.position.y);
}
}```
You'll likely need to do Player.transform.position if using a Gameobject Player instead of a Transform Player but also I recommend using cinemachine instead. So much easier and also so much better
ill look into cinemachine
Need help with my save system
The above script is the shop manager. I need to save panels that are set to false
If you're trying to save/serialize entire GameObjects or components, you're approaching this all wrong.
You need to pick and choose the bits of data that are relevant, strip those out and save those
then reconstruct your GameObjects/components from that data when you load
I kind of figured that. Im not sure how to save specific panels state active or inactive
I have been stuck on this for two weeks. starting to get frustrated. Watched like 100 videos read through multiple forums. I simply do not know what to do.
That is my store
That is my store after I clicked the purchase button on the basketball
The circles are the player sprites. PLayers collect the triangle currency in the top right. they can use them to purchase new player sprites.
SO after they purchase a sprite, I am trying to save the panel as inactive. right now if I close the game or return to the main menu the basketball will display again upon returning to the store menu
Hi, im having a bunch of problems with my script, i will explain. My enemy script has a routine, that makes him moves and stay quite randomly, it worked till now, when i put some attacking animations and more variables in my script, i need several help with that.
1st script: https://mystb.in/MinoltaHeadsMid.csharp
2nd script: https://mystb.in/FilenameRevealsAdvance.csharp
3rd script: https://mystb.in/CheckedCollectionsDistricts.csharp
Please help 
Ok I got it working for my need. All I did was add an a true or false int to my scriptable objects. So it sets panels active if the true or false int = 0
if it = 1 it sets it inactive.
Well nvm changes in the editor and saves between open and scenes but not within the build on the app
on the device
I feel like i am closer though
nvm. So over this. apparently the changes only occur within unity not the build
My polygon collider 2D isn't forming around the sprites, does it not do that?
nvm, ignore that.
hey i make a mobile game with unity but i dont now how to make that when the application closes or when u turn your phone off that u get into the pausemenu.
Can someone tell me how to do it?
Hello guys
I still without solving this issue with the enemies
But I did a little research and found that some people have issues with "prefabs"
But no one have this same issue.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I found that in the forum.
I changed the layers and set the z positions of the enemies to 0 and they still invisible on the game
So started thinking that maybe is a problem on my code. The last time that the enemies appeared on my game was before to making them prefabs, when I was setting the animations. So if have to be the Spawner script or the Monster script. But yeah, I'm noob in this so I'm not able to find the error on the code by myself.
If someone is interested I just show my code here and you can check for any error. I'm going to look for more info about it 
Check the near clipping plane of your camera.
oh no, that's actually fine
To fix this issue you shouldn't need to see code, you just need to work out what is wrong in the scene when the error is occuring
Then work out why it's getting that way
If your characters and background are at the same Z position then you will likely need to use sorting layers.
The console doesn't show any error
Who's talking about the console?
And actually the enemies have their own layer named "Enemy".
I thought the problem was that your sprites weren't appearing?
Yeah
That's an error still
The sprites only appears on the Scene screen
Not all errors appear in the console
Some of them are just... errors
Are the layers sorted correctly?
(should be the same in scene view as in the game, but worth double checking...)
What happens if you disable everything other than the enemies? can you see the enemies now?
Just to work out if maybe they're being obscured
And double check that everything is at z=0
(can turn off "2D" mode in scene view if you want to check)
Those are physics layers
The layers I'm talking about are ordering layers
They're a different thing that you set up in the sprite renderer
"sorting layer"
Regular layers are used for camera culling and physics (which you've discovered), but sorting layers are used for the order than sprites are rendered to the screen.
The enemies are in the Sorting Layer "Player"
๐คทโโ๏ธ doesn't mean anything to me
You just need to sort them in front of the background
You didn't tell me if hiding the background showed the enemies so I have no idea what your problem is
It just sounds like your sorting is messed up
Yes
You was right
My sorting layers are wrong
For some reason the enemy layers is on the back of the background
I changed the enemy over the background but they still invisible.
Well, it have to be something with the sprites of the Enemies. Because the player is visible and the enemies don't
The sorting layers are ok right now.
That's without the background
They still invisible
i had a weird issue like that earlier (except my issue was canvas elements) and just bumping the sorting order to 1 made it work. restarting unity also made it stop entirely for some reason.
I read something like that earlier. But my issue persist even if I re open Unity.
what is the Z position of the ghost @faint hollow?
Is 0
hmm.
And only one camera?
actually that doesn't matter because you have the camera preview.
Have you double checked the background is on the correct sorting layer?
You might have accidentally put it on the same layer as the enemies?
It is in the right one
The last time that the enemies were visible on the game was before making them prefabs.
Can be an issue with the prefabs?
The prefabs are visible, so maybe the problem is in the spawner
because the clones are invisible
I can't think of a reason why that would be the case if the position and sortign layer of the spawned objects is correct.
Well
I did my best to solve this today. I found some videos but none of them solve my issue
Also I read forums etc
Maybe later I'll try again
Thanks for your time man
I appreciate 
Hello! My Tile Palette is glitched and all tiles are centered
The tile palette is a prefab with a tilemap in it. If you open the prefab you can move around the tiles to where you want them.
I'm making a realatively simple metroidvania, but I need a map screen to make it a proper metroidvania. I'm currently using scene switching to go to my various rooms. How would I go about a realtively simple map screen that just shows what room(scene)you're in?
Each scene has an index number, it's just a matter of checking what index it is and associating it with a room in your map
Alternatively, you can create a script and add to your room scene that when enabled it will highlight or do whatever you want it to do with your map
That's what I was thinking, would it cause a performace hit to have images for each room on my map in the ui?
And have them with scripts on each that checks which room it is
how can i make it that unity moves the enemy 1 unit closer every x seconds?
like a grid based movement
Anyone know of a good method for intersecting/merging geometry? I'm procedurally generating a number of closed tunnels out of lines and I need them to merge when they overlap. I was thinking about tracking each tunnel as a wrapping array of lines and then doing some logic when one tunnel intersects another to generate new points at the intersection and adjust the line arrays to merge the loops of the tunnel. I have a feeling this is the wrong way to go about it
*snaps*
If you just want to know if the Player1 object is near Chest1, then you only need to do one distance check between the two of them. Not sure why you're checking the distance of each against the object this script is on.
I removed the second check and it works now, thanks!
This script works fine for the discoveredrooms part of the script(exept it does run twice when you re-enter the same room), the discoveredarea script runs forever even when the area list contains the thing i want to add?
can you give a raycast collision detection to walk on it?
no
raycast is just a query into the physics system
oh okay
How would I go about doing this?
you're checking id discoveredAreas contains the area but then adding the area to discoveredRooms
two different lists
Also - highly recommend using a HashSet for this kind of thing instead of a List, as it is faster for Contains() checks and will disallow duplicates.
please someone help, its super laggy on the right but appears to work fine on the left, how can i fix it? like in the scene its fine but in game it jitters a lot. just messing around with parallax effects
... vin?
LOL
not much
JUST FUCKING PARALLAX
2 DAYS STRAIGHT IVE BEEN TRYNNA FIX THIS SHIT
wai wai whats this ur making
^^^
just messing around with making a 2d platformer, trynna get a parallax effect running smoothly
but i c a n t
ooh nice
are u able to help me in any way btw ๐
my brain cant take more staying up till 4am
trynna fix
stuff
unfortunately i'm not really familiar with unity, more with C#, but i'll have a look for you
๐
^^^ anyone else??
yeah u to man, gl on ur project btw
thanks, you too
it's a stealth FPS, as in it will contain the usual FPS elements, but traps, silencers, tripmines, etc, are all part of the deal
doing well
sounds pretty sick, would love to see it once its finished. have u gotten pretty far or just started?
not very far
mainly working on a lobby (games and stuff can be played)
this is one of the most recent things in the mod - we gots an airport bois

:SDVpufferSquee:
is it like ridgeside with a cutscene n stuff?
anyways i gots to go, the father do be calling me
no nitro L ๐
yea 1 sec we have a concept event
aight cya later mate
the takeoff (PoC rn)
apartemtn (is purchasable)
anyways cya, lemme know what u think
that animation and quality is to die for uve really outdone ur self there
thats a large ass apartment
๐
is anyone able to help? the parallax elements seem to break in game but be fine in the scene, its super laggy and whatever
heyo
if the video didnt play in 0.1 fps for me then maybe i could look
๐
um dyu have any idea tho basically the parallax effect works fine on the left in scene but it keeps jittering on the right in game, any idea for how to fix?
you're gonna get asked to post the code.
yup
heres the parallax code
how do you move the camera
cinemachine virtual camera
show
what the cinemachine brain?
yeah
never, always or round robin
go to the other component which is on the camera or the virtual camera depending which this one is
try turning damping to 0 for a bit
ill try rq
update method, go through all of them , see if that fixes it
didnt fix
OH SHIT IT WORKED
thank you thank you thank youuuuu
๐
set them both to fixed updates
or something like that idk
that makes a lot of sense
yeah
cheers man!!
i was just looking at the camera brain the entire time and slowly going insane ๐
Grats ๐
well at least it's only slowly, I tend to lose my shit rather quickly lol
LOL
same here tbh
glad thats over jeez
I find getting excited is pretty counter-productive.. I've lost track the number of times I go to bed confused as hell, but then somehow wake up with understanding and potential solutions ๐
i just stay up. in pain but simeoultaneously (how tf dyu spell that) determined to get what i want done
and all it took was to change 2 settings that ive never seen before ๐
yeah, thats what I mean - I've stayed up days on end trying to figure something out, just getting more and more frantic and worked up - when all I really needed was a break to calm down and clear my head
true yeah, ill take that advice tho, but when you stay up all night determined to fix something and finally do it theres no bigger relief i stg ๐
The same victory doesn't really come with a next-day solution, it's more like "damn why didnt i think of that yesterday"
But, results are key, problem solved, onto the next problem ๐
yeah that makes sense probably will do that. ive never felt true true frustration yet, but im sure that day will come and i will do exactly this
anyways im off to bed
i need an earlier night for once
๐
adios!
Hey guys is the best way to shoot a bullet where I press on the screen is screenpointtoray?
Try it
Howdy, y'all. I'm trying to use the Rule Tiles (which are really cool!) to make something like a top-down 2D game --- but I'm not sure what the best practices would be for making certain rule tiles obstructions.
For example, if I have Grass, Paths, and Water as part of the same tileset (having a Custom Rule for neighbor tiles so they all work nicely together!), what would be the "best practice" way to make "Water" an obstruction?
It'd be hard to use layers here since if I'm understanding correctly, the rule tiles all need to be in the same tileset obj.
Here's the gist of what I'm talking about in sweet, sweet picture form. These custom rule tiles play really, really well with each other (!) but they've all got to be in the same tilemap. :'[ So, can't make the water a separate layer.
if you don't want to use separate tilemap layers, then you can always attach a game object that only contains a collider to the rule tile in your tiling rules.
hehehehehe... the animation isn't awful but the art is very WIP.
yah no shit ๐
btw i fixed the bug ๐ฅณ
the newer plane looks good tho right
its an honour to receive this praise
cause i most definitely deserve it by fixing it all by changing 2 OPTIONS WITHOUT A SINGLE LINE OF CODE
it took me 10 hours
some coding is really easy, vin. i think you should learn C#. i've been learning it for 2 months and i'm not doing too badly
nah i understand c# well enough im just trying to practice formatting
you do? oh
fairs
im not great at setting it all out but i can read and understand a lot of what it all means
basically when a string has another string innit
and u slap them together with an operator like a +
innit as in the string has a string in it
yee
what about string interpolation?
see i know what im talking about ๐
i love string interpolation
its basically when you take a string and give it loads of variables or placeholders
innit
if i remember correctly
well technically
an better example would be:
using System;
namespace thingy
{
class interpolation
{
static void Main(string[] args)
{
string var1 = "Dave"; //sets var1 to 'Dave'
Console.WriteLine($"Hello, {var1}!"); //will print 'Hello, Dave!'
}
}
}``` jeez writing code in discord is hell
like that ^ essentially
yes string interpolation is better than string concatenation
because string concatenation creates unnecessary string objects for every + operator you do, just to make the final string
with string interpolation or StringBuilder, there are no unnecessary string objects created
and string interpolation also looks better than string concatenation
like ```cs
string concatenation = "Variable: " + variable.ToString() + "\nOther Variable: " + otherVariable.ToString() + "\n";
//like 5 unnecessary string objects created ^^^^^
//versus
string interpolation = $"Variable: {variable}\nOther Variable: {otherVariable}\n";
is the default gravity in Unity using velocity?
it's an acceleration
just like real life gravity
yeah but how is it coded?
nobody really knows as it's closed source. But you can achieve basically the same effect like this:
public Vector3 customGravity;
void FixedUpdate() {
rb.AddForce(customGravity, ForceMode.Acceleration);
}```
ooooh i see thank you
Hey, I have a weird bug with the animation. When I animate an 2D object, I can animate any property of the object except its sprite
like this :
Did I do something wrong ?
it doesn't work when I enter play mode or when I build either
Re: rule tiles, is it possible to use rule tiles with custom layers? I was under the impression that the rule tiles all had to be in the same tilemap object to have the neighbor-thing [the auto-mapping?] work.
is there a way to make a collider just for a single color? i have a 1 color map, that's rather complex, and i don't want to have to make a polygon collider for multiple maps.
You can do layer-based collision: https://docs.unity3d.com/Manual/LayerBasedCollision.html
i'm pretty sure that's for 3d
it's for both
Project Settings -> Physics 2D ->
there's a collision layer matrix there too
does it work for a png with curves, or is it just a box collider?
okay, here is what i mean: is there an easy way to make a collider, but only for the opaque pixels in a png?
Yeah - the sprite editor basically does this already
ah, okay. do i need to make sprites in the editor then?
no
alright, thank you!
I'm pretty sure if you do this you will get what you want automatically:
- Drag image into Unity
- Set its import type to Sprite
- Drag the sprite into your scene
- Attach a Polygon Collider2D
you will get a collider that conforms to the opaque sections of the sprrite
how do i import it as sprite?
in the import settings for the image file
okay. thank you!
actually, this is what i tried. my problem with this was that it wasn't super accurate to the image, there was a gap between the side of the sprite, and the collider
in the sprite editor there's a way to set the physics shape
How could I make footsteps play in relation to the distance walked?
I'm making a top-down game and I already have footsteps playing while the player is moving but when the player is walking while hitting a wall the walk pace is slower and I'd like to reflect that in the footstep sound effects.
I've read some tips that the feet animations can help so that when the foot hits the ground the sound is played but I don't have animations, my player is a shape atm.
keep track of distance traveled (e.g. just by subtracting current position from previous position) and play the sound every 1 meter travelled (tweak the distance as desired)
Thanks @snow willow! This could work quite well I think. Hope it does sound good.
I have a 2d aipath finding script that I get from Brackeys, I have a weird error here in my script. It's telling me that "AIPath" couldn't be found in my program but when I try to run the game in my Unity it is working fine. Now I'm confused and also can't access the functions of the class AIPath
here in my editor, it's working fine
I'm so confused, i don't know if its a Unity bug
trying to rotate a point around the y-axis, but it's not working as expected and i want to make sure that my algorithm isn't the cause. here is my transform function:
// Rotates a point clockwise about the y-axis.
Vector3 RotatePoint(Vector3 v, int degrees)
{
switch (degrees)
{
case 0:
return v;
case 90:
return new Vector3(v.z, v.y, -v.x);
case 180:
return new Vector3(-v.x, v.y, -v.z);
case 270:
return new Vector3(-v.z, v.y, v.x);
default:
return RotatePoint(v, degrees - 360);
}
}
(i know my default case can cause an infinite loop, but i'm certain that i won't be passing non-multiples of 90 for degrees)
where is your AIPath class
its ok now, I just recompiled my assets
Why not:
Vector3 RotatePoint(Vector3 v, int degrees)
{
return Quaternion.Euler(0, degrees, 0) * v;
}
because i'm creating a tilemap on a grid, i want exact rotations free from floating-point inaccuracies
i won't need to rotate anywhere between 90, 180, and 270, so i figured i'd just hard-code it
ยฏ_(ใ)_/ยฏ
normally it wouldn't matter but the tiles are made to line up exactly with one another, and i don't plan to use any sort of vertex merging function, so a tile that isn't rotated exactly will result in a small gap between the edges
as it turns out my algorithm was exactly correct, it was an issue with the way i was exporting from blender. somewhere along the line my export settings got changed to -Z Forward 
I'm having some trouble with Tilemap.SetColor()
I seem to be able to adjust the colour of full blocks but can't when there is transparency in the tile.
I tried replacing the SetColor with SetTile and it worked perfectly on all tiles.
Is there some way to work around this?
my walk animation only plays when i go backward is it a code or animation problem? https://pastebin.com/rt0PY1BG heres the code
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.
soo , im working on a really bad script movement design and i stumbled into something weird ```cs
private void VerticalMovement() {
RaycastHit2D groundcheck = Physics2D.Raycast(coll.bounds.center, Vector2.down, coll.bounds.extents.y + 0.1f, terrain);
Debug.DrawRay(coll.bounds.center, Vector2.down * (coll.bounds.extents.y + 0.1f), Color.red);
while (!groundcheck)
{
velocity.y = gravity * Time.deltaTime;
}
if (Input.GetButtonDown ("Jump") && groundcheck == true)
{
velocity.y += Mathf.Abs(gravity) + jumpforce * Time.deltaTime;
}
}
after i have added the while in the script when i run it , it just completely freezes unity , cant even close it , why is that ?
because it's stuck in the while loop
yes , i thought of that but i dont se anything that could make me get stuck ,
it does
when my raycast hits ground it becomes true and when it dosent touch ground anymore it becomes false
and y character does reac the ground
yeah but when it never becomes true in the loop
if it's still in the loop, it wouldnt run your other code
the only thing you do inside the loop is set the y velocity. that means that if the condition was true at the start of the loop, it will remain true
oh right thx
i forgot that how loops work ๐
Hi all. Ive got a game using pixel art. The problem is that my laptop displays the game with a blur artefact. Particularly when running. If I screenshot during the run, it looks fine. So I assume it's to do with my display and refresh rate. It's a 144hz monitor. The thing I don't understand, is that when I test pixel art games on steam, they look fine. So why does my game have this issue?
Game looks fine if I export to my phone. Just my laptop has this issue.
maybe a video might help illustrate what you mean?
is there any way to trigger mouse down on multiple 2D colliders? they are box colliders2D but I can't just check if it's in centre +/- width/2 as they may be at an angle
Bit tricky. If I screen record (on laptop) then play it back on my phone, it looks fine too lol. I'll need to record off-screen. It won't look very good but hopefully you can see it. Here it comes...
You can see a slight ghosting (blur) effect
hm okay ๐ฎ sorry I have no clue, but hopefully that helps other people seeing this
Slightly clearer clip (again, off-screen footage)
I've tried fixing the frame rate to locked ,60fps as well as toggling vsync
this makes it sound like it is just an issue with your laptop display and not an issue with your code
Hm, but I also downloaded other pixel art games and they don't have this issue on my laptop. So I was thinking it might be an export setting, code issue, or something else (sorry not sure what channel is best to ask this question).
Hello, I'm having a confusion and issue with 2d raycasthit. I don't know why I'm not detecting any gameObject from my hit. Is my code wrong here? The position data is right since I'm also looking at the drawnGizmo in my game view.
RaycastHit2D hit = Physics2D.Raycast(trackedFinger1.position, -Vector2.up, 10.0f);
GameObject hitObj = null;
if(hit.collider != null)
{
hitObj = hit.collider.gameObject;
}
if(hitObj != null)
{
Debug.Log(hitObj.name);
}
else
{
Debug.Log("no object");
}```
is my Raycast parameters right?
it's ok now, I've just change the Ray to Ray2D since I'm working in a 2d platform i forgot.
Vector2 r = Camera.main.ScreenToWorldPoint(trackedFinger1.position);``` then transform to this
can I move the demi circle to be on top of the platform?
This may be too obvious but if the LockColor flag is set (either in the tile asset or via changing it on the tilemap component) then SetColor does nothing. The color is saved within the Tilemap and the tileflags can inhibit changes to Color, Transform etc. Hope this helps
just my inexperienced two cents but that system looks like there'd be a y offset box somewhere? try looking for that if you can
@spiral solar thank you I had no idea that was possible. Probably didn't search the right keywords.
this one aspect of tilemaps confuses people all the time so don't feel bad - see it all the time on reddit and unity forums (fora?)
there is a better way to do this
this.transform.position = mousePos;
if (mousePos.y<bottom && mousePos.x>left && mousePos.x <right)
this.transform.position = new Vector2(mousePos.x, bottom);
if(mousePos.y<bottom && mousePos.x <left)
this.transform.position = new Vector2(left, bottom);
if (mousePos.x < left&& mousePos.y > bottom && mousePos.y < top)
this.transform.position = new Vector2(left, mousePos.y);
if (mousePos.x < left && mousePos.y > top)
this.transform.position = new Vector2(left, top);
if (mousePos.y > top&& mousePos.x > left && mousePos.x < right)
this.transform.position = new Vector2(mousePos.x, top);
if (mousePos.y >top && mousePos.x>right)
this.transform.position = new Vector2(right, top);
if (mousePos.x > right && mousePos.y > bottom && mousePos.y < top)
this.transform.position = new Vector2(right, mousePos.y);
if (mousePos.x > right && mousePos.y <bottom)
this.transform.position = new Vector2(right, bottom);
I can't even read this. What is it supposed to be doing?
moving gameobject in restricted area
mousePos.x = Mathf.Clamp(mousePos.x, left, right);
mousePos.y = Mathf.Clamp(mousePos.y, bottom, top);
transform.position = mousePos;
@runic orbit ๐ค
ohh god. it's so easy ๐ thanks
if i want to check whether my player is close enough to an NPC to talk to them, should i use a collider to monitor that or is there some other component thats better suited for this?
A collider would work fine, yes.
Especially if you intend to have something popup above their heads to indicate the place can speak to them.
yes, that sounds like what i want
can i mark a collider as something that has nothing to do with physics though? (currently the collider i have for this talking-range area is stopping my character from advancing in)
ah, i think i found what i was looking for with the Is Trigger option:
The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger objectโs scripts.
Yep, Triggers are specifically for this kind of thing. Detecting when something is near something else.
hello, I'm trying to make my ragdoll's arm look where my cursor is when I press a button, but this isn't working at all, it isn't moving the arm at all
void Update()
{
Vector3 cursorPos = new Vector3(cam.ScreenToWorldPoint(Input.mousePosition).x, -cam.ScreenToWorldPoint(Input.mousePosition).y, 0);
Vector3 difference = cursorPos - transform.position;
float zRot = Mathf.Atan2(difference.x, difference.y) * Mathf.Rad2Deg;
if (Input.GetKey(mouseButton))
{
rb.MoveRotation(Mathf.LerpAngle(rb.rotation, zRot, speed));
}
}```
ping me if you reply.
hey guys so i got a issue where i want a enemy to shoot bullets but cant really find any good guide/tutorial on it besides one i found but that code does not seem to work since it makes my game lag super hard anyone done this before and wont mind helping me out?
I want to move an object towards another object, like the Vector2.MoveTowards method, just that it is moved with a rigidbody and velocity. Whats the best way of doing that?
You can use MoveTowards together with rb.MovePosition
or just set a velocity in the direction of the other object
How do I do either of these?
MovePosition works just like transform.position =
Yeah but I dont see how I can ise that to apply velocity
for the velocity approach, you can calculate a direction vector from A to B like (B - A).normalized;
then just multiply that by your desired speed
and that's your new velocity vector
Oh and also mymobjects with rigidbodies have a constant negative x velocity even when they arent moving. Why does that happen? Can that mess anything up?
no idea what you're talking about
we're talking about setting the velocity though so it shouldn't matter as you'll overwrite any existing velocity it has
Not sure how I can take a screenshot, but all of my objects with a dynamic rigidbody that arent moving have a negative x velocity. I guess it doesnt make a difference when setting the velocity, but I get some problems whith detecting it
Also, what would be the context of this? Im not sure what .normalized is, and Im not sure how exactly I can use this to calculate what velocity I have to apply
B and A are the positions (Vector2 or Vector3) of your two objects
given that, it's the literal code to calculate the direction vector
Hm okay Im going to experiment with it so that I see what it does
normalized gives you the unit-length vector in the same direction as the vector it's called on
And does it return a vector2?
if B and A are Vector2, yes
Okay I think I finally understood it, took a while because that was new syntax to me
how do you teleport it?
By setting transform.position
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PortalController : MonoBehaviour
{
public Transform otherPortal;
public Vector3 playerWarpOffset;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
collision.transform.position = otherPortal.position + playerWarpOffset;
}
}
you're not supposed to move transform yourself (via code) when under control of the physics engine. IIRC you have to change to Kinematic mode then switch back.
Nah, if you teleport, thats fine. you just gotta save the velocity of your rigidbody and set it back after teleporting