#๐ผ๏ธโ2d-tools
1 messages ยท Page 25 of 1
oops
you should do
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal"), rb2d.velocity.y)* speed;
hum wait
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal")*speed, rb2d.velocity.y);
now this should be right xD
I seem to only move right
so you won't need that
//limits the players speed
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
well I don't think so
how do i use the sprite collider thats used for tilemapcollider2d with normal sprites
Hi there. I was wondering is it possible to create a blank 2D texture and then copy portions of various other textures onto it? Am trying to create a 2D sprite that's a composite of other images.
@pearl patio It is odd, when I remove
//limits the players speed
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
It works properly but the speed is not reduced, when I keep it the speed is reduced but I can only move right even if I press the left key (the left animation plays though)
At the top of the script
wait show me your whole script
public class Player : MonoBehaviour
{
public float maxSpeed = 3;
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
private Rigidbody2D rb2d;
private Animator anim;
// Start is called before the first frame update
void Start()
{
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
//move left
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-0.23f, 0.23f, 0.23f);
}
//move right
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(0.23f, 0.23f, 0.23f);
}
//jump with spacebar
if (Input.GetButtonDown("Jump") && grounded)
{
rb2d.AddForce(Vector2.up * jumpPower);
}
}
private void FixedUpdate()
{
//left/right movement
float h = Input.GetAxis("Horizontal");
//moves player when movement keys pressed
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb2d.velocity.y);
//limits the players speed
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
}
}
how do i use the sprite physics shape that is used for tilemap colliders for normal sprites
first, why that ?
//move left
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-0.23f, 0.23f, 0.23f);
}
//move right
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(0.23f, 0.23f, 0.23f);
}
you should flip the sprite than changing it's scale
https://docs.unity3d.com/Manual/CustomPhysicsShape.html
This should help you
I tried what you typed earlier but it doesnt seem to use my walking animation
and you don't have to put rb2d.velocity in a fixed update, it already use fixed delta time
My player doesnt seem to be able to move left
I think it could have something to do with
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb2d.velocity.y);
put a Debug.log (new Vector2("Vector 2 :" + Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity) in update and send the values please when you try to move to the left
sorry I misstype
write
Debug.log ("Vector 2 :" + new Vector2(Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity)
oh
well I'm dumb
Try that so
Debug.log ("Input :" + Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity)
ok so if i change the sprite in a sprite renderer, how can i get the polygon collider to update to match the custom physics shape of that collider
I am trying to make the sphere scale with velocity
do you know why the collider isn't scaling with it?
The arc is it going around a warped collider
My code:
Vector2 dir = rb.velocity;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
if (speed > 0)
{
transform.localScale = new Vector3(1 + speed*stretchScale, 1/(1 + speed*stretchScale), 1);
}```
ok so if i change the sprite in a sprite renderer, how can i get the polygon collider to update to match the custom physics shape of that collider
Iโll try it when I get home tonight, thanks for the help thus far
first is right, second is left @pearl patio
how do i make it so that a rigidbody2d cannot be affected by other physics objects
ok i just set the mass ultra high and that did the trick
isKinematic
no i still want it to fall and stuff
but just not be able to get moved by other physics objects
Set up layers
eh its fine setting the mass to 10000 worked just fine
Not the most performant thing to do
yeah, shortcuts may come back at you later ๐
In a 2d game, how would I program a npc to look at the player? I need to figure out specific directions (left, right, up, down). I need to be able to call specific animations based on which way the npc will end up facing.
you should check the positions of both for example, then you can determine through math, where the player is.
I decided to use Vector2 dir = (player.transform.position - transform.position).normalized; in order to find the direction. Though now I'm running into an issue where it is reporting Vector2.left is actually down......2 steps forward, 20 back....
can some one help me i wanna trap my cam in a box depending on its size just like treating the cams view area as a collider trapped in a box, how do i do dis?(my game is 2d)
ohh okay i thot i could get away from not using cine machine oh welp
okay
Ok so
Today I made a simple pause menu but for some reason, I cant go to the menu
I get this error (ignore the warnings)
The thing is that I have the Menu in the build settings
ye
can i also see ur build settings (sry if i ask to much im not sure how to do it)
i know why
ur name of d scene and d one ur trying to load arnt d same
SceneManager.LoadScene("Menu"); dis is wrong
ok
So I should rename it to MainMenu?
ye
ok thanks
Just make sure EVERYTHING is d same when naming scenes
{
GetComponent<Animator>().SetBool("Walking", true);
}
else
{
GetComponent<Animator>().SetBool("Walking", false);
}
if (Input.GetKey(UnityEngine.KeyCode.D))
{
GetComponent<Animator>().SetBool("Walking", true);
}
else
{
GetComponent<Animator>().SetBool("Walking", false);
}``` why does the animation only play when i press A?
??
you should design that differently
replace all of that code with
bool isWalking = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.A);
GetComponent<Animator>().SetBool("Walking", isWalking);
@median zenith
|| means or
&& means and
@pearl patio I just needed to add * Time.deltaTime
wait how can this fix your problem
I do not know, but I can now walk left and right properly
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed * Time.deltaTime * 2, rb2d.velocity.y);
So I have
public class Player : MonoBehaviour
{
public int curHealth;
public int maxHealth = 100;
void Start()
{
curHealth = maxHealth;
DeadUI.SetActive(false);
}
void Update()
{
if (curHealth <= 0)
{
DeadUI.SetActive(true);
Time.timeScale = 0;
}
}
}
}
It doesnt seem to display the Dead screen when I hardcode the health to 0
@upper wedge You IDE would've told you that it doesn't exist in this context.
Or you've created a class with faux static SetActive method.
Well it is odd because when I set it to 0 it displays the dead screen a couple seconds later once I move my character but it does not set the timescale to 0 I can still run in the background
create a field serializable in the inspector, set a reference, then run SetActive on that.
I'm not quite sure how to do that exactly
I fixed it, sorry
It was simply I had the code in the wrong spot
But one other thing
When I update my
public int curHealth;
public int maxHealth = 3;
In my script
This value doesnt change automatically
Should I just change it manually?
Inspector value overrides the default value; what you set in code as default during declaration.
You can hide the value of you do not want inspector modification and it'll be the default since someone/yourself hasn't modify it through the inspector; using the hide tag.
usually better using https://docs.unity3d.com/ScriptReference/NonSerialized.html Because you can serialize it, hide it, forget about it, and still use hidden default value. This will remove serialization. Or use internal instead of public to have project wide access without default serialization.
@still tendon Don't cross-post, please.
I will take care, sorry
How can I get this movement functionality in 2D mode?
Why not just make the project in 2d
private void OnTriggerEnter2D(Collider2D obstacles)
{
if (obstacles.gameObject.CompareTag("Traps"))
{
curHealth--;
}
}
I have this basic code
My health lowers for this ground trap
But not the wall one
Neither of them are set to trigger mode; isTrigger is false. Neither should be working.
Unless you've got some tech-magic occurring, neither should be working @upper wedge
Wait, this script is on player... so.. 
Should work.
Unless your horizontal trigger collider is less than that of your collision collider and prohibits your trigger collider from touching the spike..
is there a SetPixel() type function for tilemaps?
https://pastebin.pl/view/942775dc Can I get help please? Im trying to make a matrix, n 2D array for a tetris game
but it wont work
the pieces would appear like 1 million of times at once
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
This is how it looks in Unity
This is how it looks when I build it
Any idea as to why?
They are both in a canvas
Yeah they are
Screen resolution differs.
How come everything else stays the same?
In other graphics library this is considered extended viewport (last I recalled) and what you'd want is either stretch/shrink or fit viewport (black bars). I don't believe these other types of viewports are natively supported so you'll have to do some fiddling with Camera.orthographicSize or some other means. A quick web search would probably provide plenty of workarounds as I can imagine this situation being quite common.
This is my first time getting this error
I am not sure what to do
I think I need to rename something
First time? Good job. It's a pretty common error that is informing you that you're trying to access a member variable of an instance but the instance is null. Your error is pointing to the pipe spawner script and on line 25. Perhaps the variable is null?
So your list is null
You should assign it a reference of new list during declaration or start.
In line 7
This occurred because the list is still null but you're trying to access the Add method.
[SerializeField] GameObject pipePrefab = null; // Prefab of the pipe object
The list is null according to the error. Unknown if your prefab is as well, with the supplied error; no other errors so highly unlikely that prefab is null.
Doc on list constructor: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-5.0, look to the examples for guidance. Your prefab/reference of object isn't the issue..
Ok
I'm on mobile phone and cannot provide code without great difficulty.
So, I have written this code to instantiate Obstacles every specific intervals. That's working fine, but, I also want to have the Obstacles have a rotation of either 0 or -90 on the z axis. How could I do it?
Put a quaternion.euler on the rotation with your random z rotation @arctic yarrow
ok, thanks!
how do i use this script with tilemaps?
im working on my character controller:
https://streamable.com/erze6b
but i have issue, it will weirdly jerk the player sometimes.
the platforms are really snuggly together, simple box colliders, they are copypasted so there shouldnt by any offset in their positions. player is using capsule collider. i can show code of anything but im unsure what is relevant to this. movement is simple velocity based rigidbody.
any ideas whats causing it?
I guess there is still some weird thing going on with those gabs in there, at least it looks like that.
You could checkout combound colliders tho, they may fix that issue, but just a guess @fiery yarrow
worked like a charm ๐
๐
Love that game honestly ๐
I guess you just put like all colliders into one compound? But just wondering, are you not freezing your rb rotation on Z?
i am
but then its my custom character controller so who knows whats wrong with it. (not me for sure)
i wasnt touching it there btw its just what it does by itself, no input
oh i see adding the composite collider added a rb to the map itself, hence it was falling with my character and freaking out. that makes sense
adding this shape collider instead of a capsule works much better, but it makes me wonder why i never saw it used anywhere before and what else might go wrong with it
Does making your world rb static work for the level?
nope, i will have moving parts
your groundcheck is a trigger?
Or is it possible that you are colliding with that little collider on the gaps?
and what is this? rigidBody.velocity = new Vector2(x, rigidBody.velocity.y + 0); ๐ like, adding 0, guess just in development ๐
yeah thats my stairs climber replaced with a 0 so im sure its not that messing with it
no, player has no children with any colliders
Or can you just create a very wide collider for this to test, so that your character is really just having issues with the gaps
yes, i have, it is buttery smooth with a single large collider
hm, weird. Can you overlap two boxes and see, if this gives you hikups?
i tried giving my platforms a bit of an overhang so they overlap into each other, no difference in result
or did you mean it in a different way?
Nah, i meant it that way. Weird, hard to tell without having your project open: I would just replace my character with like a custom 2d one and check if it still happens there.
custom 2d one?
Just for clarification, your ground things are just box colliders without any rotation, right?
yes
yeah not your own character controller script
i mean, im literally just giving some horizontal velocity to that rigidbody, and it gets stuck on the edges somehow
googling the issues showed many people having similar problems, though none of their solutions have worked for me so far
if i give my character a box collider for main with sharp edges, it gets literally stuck. with rounded, it just gets bumped
Weird, are you like working in a tiny scale?
No, sounds legit actually. I will try later, gotta take my little one out gettin some fresh air ๐
Be back later, maybe we can find a solution
Hi everyone, I have a question : is there any way to draw a 2D shape directly via Unity, or do I have to create a sprite of said shape in another software before ?
This counts as a collision using OverlapBox and OverlapCollider
https://gyazo.com/ec7907275b2d1f51993ac60e96a1e014
Is this normal behavior?
Collider2D c = Physics2D.OverlapBox(bCollider.bounds.center, bCollider.size, 0, collisionMask);
if (c)
print("hit1");
ContactFilter2D cf = new ContactFilter2D { layerMask = collisionMask };
Collider2D[] res = new Collider2D[1];
int resN = bCollider.OverlapCollider(cf, res);
if (resN > 0)
print("hit2");
you can create mesh from code yes
@fiery yarrow sorry I meant in the editor, for example quickly drawing a test map
well for quick prototyping shapes there is probuilder, you should be able to make just flat 2d shapes with it.
there might be better tools for specifically 2d around
i dont think you can easily do it from the editor out of the box, but someone correct me if im wrong
Oooh I didn't think about using probuilder
Thanks for your answer !
I'll look into it
there is a default contact offset in project settings -> physics 2d, does that help?
im not sure if that affects overlaps or just physics simulation itself
@fiery yarrow Ah, i saw that. I'm not using it in a physics simulation so that doesn't matter. But i think i need to find another solution instead of changing default contact offset project wide. Ty anyway!
Hi, i'm looking for having all tile position of a tileMap can somebody help me?
so, i have a skeletal animation, but when i added the Sprite Render Flipx thing, it either didn't work, or only did one part of the body
Um I think I misunderstand lerp
I though that if I were to for say... lerp velocity to 0, 0, 100 by 3 * time.deltaTime it would accelerate to it at 3 per second
so what I am currently using is trying to make it follow a player at a certain speed constantly
but moving the player away at like 5 m/s with .025 * time.deltaTime as the lerp, it only falls behind to a certain point
then it becomes constant
What would make it always go to the target at a certain speed but never over?
Would I have to just add the direction twards it and clamp it?
no...
that would only work 1 way
hmmmmmmmm
Cant beleive I never noticed till now
im confused
so what does lerp do anyway?
Is it like if I have .5 it goes half the wayy there?
I only started to find out I was using it wrong when I noticed using it to accelerate a character they would slow down faster by reversing direction rather than stop giving it velcoity
it move between a and b smoothly, if you using deltatime as multiplier it will move a bit each frame by that much
yeah
as in 1, 10, 3 would give 4
if you go to 1 to 10 by 3 it will move by 3 3 3 1
or something around that
its probably all written in the doc
back
Description
Linearly interpolates between two points.
Interpolates between the points a and b by the interpolant t. The parameter t is clamped to the range [0, 1]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between those points).
ok thats what I though
hang on
grabbing some code
transform.position = Vector3.Lerp(transform.position, followObject.position + offset, initialFollowSpeed);
the initial follow speed is .025
but as you see
well
not see
but it lags behind a moment
then starts coming at the same speed
like dampening
it starts on back then slows its fallback and starts catching at a certain distance
yesysysys
iuahg
Yeah its not going right
it said .5 would return the middle
So i have to divide it by the difference between a and b
AAARG
i mean i got it
but still UNITY WHY MUST YOU BE WEIRD
nope not working
AAAAAAAAARG 2.0f!
dont you just need like 0.5f * Time.deltaTime
if you have a speed you can just add it to that i think?
i suck at math i dont know but thats how ive seen it
nonononononoonnoononononon
it mean that if every time it returned .2
and i had 0 as A and 1 as B
then
it goes to .2
.36 next
thing is A will change every frame
then .448
yeah
im counting that
it starts 0, then .2, then .46, then .448
etc
not the 0, .2, .4, .6 I want
OK lerp has always done that
it doesnt go like (0, 10, .1 ) a, b, interpolation with an output of .1 .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1...
if you want to move just by a certain value why dont you translate or something
instead of using lerp
had to write a script to calculate for me cause im lazy
1, 1.9, 2.71, 3.439, 4.0951 etc
thats what the lerp does
My original code:
transform.position = Vector3.Lerp(transform.position, followObject.position + offset,initialFollowSpeed + (followSpeedByDistance * (transform.position - followObject.position).magnitude) * Time.deltaTime);
how would I change the lerp out
if you want to use lerp to consistently move towards something then you need to have a start and end position cached
otherwise just use MoveTowards
ohohoh
there is Vector3.MoveTwards
I can swap it with that
Welp i need a new method for smooth camera movement
case movetwards is fiddely
so...
what can smoothly move a position?
Vector3.SmoothDamp
cool
This SmoothDamp be kinda shaky
It has small but noticeable jumps
any idea what thats for?
Any fix?
here lies the resting place of a gif
It would have had a longer life but I remembered how strict the admin are about gifs
uh
Im new at it
I just picked a tutorial
EXPAND for Time Stamp Links -- This is the most basic Unity tutorial I will ever make. If you are brand new to Unity, or if you want to make sure youโve covered the basics, and if you want to learn how to write your first C# script - this is the video for you!
Over the course of 2 hours, I go through the User Interface, Game Objects, Transforms...
my first tutorial
Anyone know how to fix the jitter issue with smoothDamp? (FIXED)
Hey
I am using this code:
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth
{
public float health;
public float maxHealth;
public Vector3 healthBarOffset;
public GameObject healthbar;
}```
I am planning on using it to add it into antoher script
how do i combine it with another script?
I ping u
:D
xd
Please do not spam, people will answer in due time if they have the answer
sorry ive been waiting 20 minutes
you may be using a rigidbody without interpolation and are moving in update
it's unclear
" combine it with another script" doesn't make sense
hang on
If you're talking about inheritance, you should watch a tutorial
Basicly I want it to look like this:
Settings area 1
Settings area 2
so you can open it
just make a public variable of your type
I have this:
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth
{
public float health;
public float maxHealth;
public Vector3 healthBarOffset;
public GameObject healthbar;
}
I want thoes variables to be put in another script
Just make a public EnemyHealth in your other script
you need to make your EnemyHealth serializable
add [System.Serializable] above it
(the class)
any idea why this happens when you create a gradient using SetPixels with a color array?
left side should be completely white but turns into red at the end
and right side the same but it turns to white
I assume your texture's wrap mode is wrong
you're right, i set it to TextureWrapMode.Clamp and now it works as expected!
thanks ๐
how can i make a pendulum type thing
im trying to make an axe that swings back and forth
does someone know how i make a text stand still, because if i move ma character the text moves with him, but i want it to stay in the speech bubble
I need help with the trail in Unity 4.12 2019
It keeps on overlapping my character
Who here can help build a Simple dialog system for NPCs
im doing the same thing lol
Consider using object text with text mesh pro and child it to the chat bubble. Else translate the text by getting the world to screen coordinate of the chat bubble and adjusting the text position by that amount; first prefer.
@uneven rune don't make it a class. Make it a method instead. Then you can call it to your main
How do I rotate a object by a certain angle?
Transform.Rotate
ok
thx
How can I get the rotation as a vector3 tho?
I want to make knockback on a bullet and need the direction it is going
can anyone help
hoping you just forgot to give the ground collider the Ground tag but it's more sinister than that huh
on what line
on the ground gameobject
should be able to find it at the top of the inspector when you have the ground selected
is it better to use velocity to move in 2D or is it better to use force when a rigidbody is being used?
Can someone pls help me with these errors
@elfin sandal There's good and bad things with both. Velocity is generally better if you want snappy 2D movement (hollow knight esque)
I see
does it make it so you don't go max speed when starting to walk with force?
well, force can be more annoying to work with.
It adds a force to what you already have.
Setting a speed limit can be more annoying that way
with velocity it just goes to a set number and stays there.
ohhh
basically check if it's beyond what it's allowed to be. If it is, null that movement vector
not null
but ya know, 0
so I have a 2d game that's top down, I want the mouse to move the camera based on the disance of the mouse from the player but when it moves it affects the distance and it's a sporatic camera
what's the right way to do this?
should I have it be based on the center of the screen or something?
From what you described, you have the distance based on the mouse and the camera position.
You probably want to use the distance between the mouse and the player object in world space
which means you have to get the world space position of the mouse
oh yeah i meant player
here's a vid
and code
mousepos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
//Vector3.Normalize(InputLook);
//print("cam to screen mouse is " + Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue()));
//print("mouse pos is " + Mouse.current.position.ReadValue());
//print("normalized input look is " + mousepos.normalized);
lookaheadDir = mousepos - (Vector2)transform.position;
print("mouse being moved mouse dif is " + lookaheadDir);
LookAheadTransform.position = transform.position + new Vector3(Mathf.Clamp(lookaheadDir.x, -2, 2), Mathf.Clamp(lookaheadDir.y, -2, 2));
return;```
lookahead is where the camera will go
You really cannot do it like that
ok its diff than what I expected, but I think I can try to explain this
you should add an offset to your camera based off of the mouse position from the center of the screen
it doesn't matter what space you use
I don't know how to do it
If you divide the offset by a few (Let's say 5) it will also give you a less 'sensitive' mouselook
the difference?
the difference (-2 and 2) (i assume) is the min/max
but you can make it less sensitive by dividing it
after that you can adjust min and max to your preference
Replace it with
LookAheadTransform.position = transform.position + new Vector3(Mathf.Clamp(lookaheadDir.x, -2, 2), Mathf.Clamp(lookaheadDir.y, -2, 2)) / 5f;
Maybe then you see what I mean
if you could make another vid, I can see if there's another thing to focus on. But it will definitely be 'less sporadic'
However you might want to expand the limits of -2 and 2 to -10 and 10. But that's some variables that I can't really preview in my head ๐
Vector2 screenSizeHalf = new Vector2(Screen.width, Screen.height) / 2f;
Vector2 offset = (Mouse.current.position.ReadValue() - screenSizeHalf);
offset = new Vector2(offset.x / screenSizeHalf.x, offset.y / screenSizeHalf.y);
lookAheadDir = transform.position + new Vector3(offset.x * multiplier, 0, offset.y * multiplier)```
That's my random code that I've written entirely in discord
it would need clamping too
Discord needs a specific 'Discode' mode
thanks ๐
can someone help me with my code?
i want to animate the NPC but it doesnt work
just the animation
i am using blend trees
ok
What would be better for a camera follow player in 2D
Cinemachine
Or
Code the script
Code the script so you know how everything works
Ok
Relying on someone else's code will be problematic, cuz it might it stop working in subsequent updates
True
if ur own code stops working due to changes to the API
you'll be able to change it easily since you'll have thorough knowledge of your own style and you'll remember what you did
how can I fix this shaking ? It happen when I add the pixel perfect on my main camera
How do I make an object rotate towards another?
I forgot
just point straight to it, no rotate over time needed
@uneven rune LookAt
ok
wait
how exactly
cant find "lookAt"
oh
googled it
found it
More complicated question:
How can I calculate the angle to shoot a gun at a moving target? The bullet has 0 gravity, the player has 0 gravity.
(static launch speed)
Hey Iโm trying to make an arena thing where you walk in the camera centers in the room and the doors close behind you until the enemyโs are gone how might I go about that
do some know how to make the c# script generate random numbers
using System.Collections.Generic;
using UnityEngine;
public class upfast : MonoBehaviour
{
public float someSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.up * someSpeed * Time.deltaTime, Space.World);
}
}
@uneven rune simple, you just subtract the two vectors. Now you have something that points towards the other vector. You can normalize it and then have a force multiplier
Suppose you have two GameObjects
GameObject player, GameObject turret (ignore the syntax , it's just pseudo code)
vector dir = (turret.positon - player.position).normalized
Bullet.rigidbody.addforce(dir* forceModifier);
Or the Unity equivalent: https://docs.unity3d.com/ScriptReference/Random.html
@low lion you didn't unerstand the question did you? Shoot it at a moving target
the target is moving at a constant rate
where do i shoot the 0 gravity projectile
Well thats over anyways
Heres a different question:
How do i get the rotation of a object as a directional vector3?
transform.rotation * vector3.forward does not work
neither does transform.forward
wait this is 2d code section and im doing 3d
i got quite a small problem. which is, i cant assign sprites to empty objects while running. there are no errors and anything heres the script if youd like to help me
using UnityEngine.UI;
public class HeroCalculation : MonoBehaviour
{
Vector3 spawnPos = new Vector3(-26, 0, 0);
string[] heros = {"berserker", "tank", "wizard"};
public Sprite berserkCard;
public Sprite tankCard;
public Sprite wizardCard;
public void spawn()
{
int hero = Random.Range(0, 3);
Debug.Log(hero);
GameObject card = new GameObject(heros[hero], typeof(SpriteRenderer));
card.GetComponent<SpriteRenderer>().sprite = berserkCard;
card.transform.position = spawnPos;
spawnPos.x += 4f;
}
}```
mkay im just hella dumb and forgot to add the sprites to the public sprites
Hey, which way of doing 2d character platform movement is the best?
idk
prob a script in the fixed update method
and applying force to ridigbody
idk im new to unity
oh also a ridigbody2d compent and collider
why cant my unity know what RigidBody2D is?
{
// Start is called before the first frame update
void Start()
{
}
public Animator animator;
public RigidBody2D rb;
.........```
Do you have
using UnityEngine;
at the top?
Yeah, the issue was camelcase :/ lmao
You should set up your VS properly if it isn't. It should tell you what the right name is as you start typing Rigid... and then you can just select it
Yeah I mean Iโm using VS Code
how do u type like that in discord with that black outline thing
Both sides
Np :p
If you want to use C# highlighting with it you can do
some text
```
a
poly = gameObject.GetComponent<PolygonCollider2D>();
hitObjects = Physics2D.CircleCastAll(transform.position, shadowCastRadius, Vector2.up, isWall);
Vector2[] paths = new Vector2[hitObjects.Length * 16];
for (int i = 0; i < hitObjects.Length; i++)
{
if (hitObjects[i].collider.gameObject.GetComponent<ShadowObject>() != null)
{
ShadowObject tmp = hitObjects[i].collider.gameObject.GetComponent<ShadowObject>();
for (int j = 0; j < tmp.objectVerts.Count; j++)
{
Vector2 angleVector = (tmp.objectVerts[j] - new Vector2(lightCaster.transform.position.x, lightCaster.transform.position.y));
RaycastHit2D ray = Physics2D.Raycast(lightCaster.transform.position, new Vector2(angleVector.x - 0.0001f, angleVector.y - 0.0001f), rayDistance, isWall); //at the exact pos of the verticy of the object
paths[(i * 16) + (j * 4)] = ray.point;
Debug.DrawLine(lightCaster.transform.position, ray.point);
paths[(i * 16) + (j * 4) + 1] = lightCaster.transform.position;
ray = Physics2D.Raycast(lightCaster.transform.position, angleVector, rayDistance, isWall); //at the exact pos of the verticy of the object
paths[(i * 16) + (j * 4) + 2] = ray.point;
Debug.DrawLine(lightCaster.transform.position, ray.point);
ray = Physics2D.Raycast(lightCaster.transform.position, new Vector2(angleVector.x + 0.0001f, angleVector.y + 0.0001f), rayDistance, isWall); //at the exact pos of the verticy of the object
paths[(i * 16) + (j * 4) + 3] = ray.point;
Debug.DrawLine(lightCaster.transform.position, ray.point);
}
}
}
poly.SetPath(0, paths);
im trying to make a LOS system
I can see the lines fine when I debug and it looks correct but the backend, the points are ALL over the place
I have no idea y
can someone help me pleas?
not like that
Please do not cross-post and just ask your question in an appropriate channel.
I am trying to move a character and wall jump, but the movement is overriding the x movement. If i dont override, he can gain infinite speed if walking in the same direction. How do i fix this? I did this
public void Move(float horizontal)
{
//Add air control
//Add slip movement and not instant
if (horizontal<0)
{
transform.localScale = new Vector3(-startScale.x,startScale.y,startScale.z);
}
else if (horizontal>0)
{
transform.localScale = startScale;
}
//rb2d.AddForce(new Vector2(horizontal*speed,0),ForceMode2D.Force);
rb2d.velocity = new Vector2(horizontal*speed,rb2d.velocity.y);
}```
public void Jump()
{
/*
if (playerState== WalkingState.Grounded || (playerState == WalkingState.Air && (fowardCheck|| backCheck)) )
{
canJump = true;
}else if (playerState == WalkingState.Air )
{
canJump = false;
}
*/
if (playerState== WalkingState.Grounded)
{
rb2d.AddForce(Vector2.up*jumpForce,ForceMode2D.Impulse);
canJump = false;
}else if (playerState == WalkingState.Air)
{
if (fowardCheck)
{
rb2d.AddForce((-transform.right)*jumpForce*2,ForceMode2D.Impulse);
Debug.Log("Jumped Wall");
canJump = false;
}
}
Debug.Log($"Jump from {this.name} worked");
if (canJump)
{
rb2d.AddForce(Vector2.up*jumpForce,ForceMode2D.Impulse);
canJump = false;
}
}```
private void FixedUpdate()
{
if (_moveAxis.x !=0)
{
currentMovement.Move(_moveAxis.x);
}
}
void HandleInputs()
{
_moveAxis = controls.Player.Movement.ReadValue<Vector2>();
}
void HandleJump(InputAction.CallbackContext ctx)
{
Debug.Log("HandlerWorked");
currentMovement.Jump();
}```
I dont know how to fix this
@inland glen Use a field variable to collect all of the input, then apply it in one place.
public void Move(float horizontal)
{
//Add air control
//Add slip movement and not instant
if (horizontal<0)
{
transform.localScale = new Vector3(-startScale.x,startScale.y,startScale.z);
}
else if (horizontal>0)
{
transform.localScale = startScale;
}
//rb2d.AddForce(new Vector2(horizontal*speed,0),ForceMode2D.Force);
if (Mathf.Abs(maxVelocity2D.x)>=Mathf.Abs(rb2d.velocity.x + horizontal*stepSpeed))
{
rb2d.velocity = new Vector2(rb2d.velocity.x +horizontal*stepSpeed,rb2d.velocity.y);
}
}
I did this
it works
but i dont know if its the best aproach
Hi everyone, I'm new here - just want to say - good luck for all of your projects and hang in there! ๐
You too man!
Hello
hi brothas how do i use IEnumerator and StartCoroutine inside a trigger 2d if it's even possible i mean
you call OnTriggerEnter2D and set there your StartCoroutine(Whatever());
Anyone know how to calculate the launch angle of a 0 gravity projectile with a fixed speed to a moving target with 0 gravity?
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html @uneven rune should get you goin
Hey Guys ๐ , i just noticed Unity has a CharacterController component, i'm not sure what's the use of that exactly and the docs are not too helpful, do you know any resource with a decent explanation/tutorial? I just want to understand if it's something that can save me some time in handling the character (i intend to use it in a 2d context)
groundCheck = Physics2D.BoxCast(
new Vector2(transform.position.x,
transform.position.y - (sensorYDistance / 2) -
(transform.GetComponent<BoxCollider2D>().size.y / 2 * transform.localScale.y) - sensorYOffset),
new Vector2(
(transform.GetComponent<BoxCollider2D>().size.x * transform.localScale.x) +((transform.localScale.x > 0) ? -sensorXThicknessReducer : +sensorXThicknessReducer),
sensorYDistance),
0,
Vector2.down, 0, walkable);```
i am making a character movement script and the ground check only works when the scale is positve (when the player is moving to the right) and when its negative (the scale value its the same) it doesnt collide with anything but it should
the gizmos is copy paste of that and it shows correctly
why cant i see the knob ingame
i know its not code but i dont know where this belongs
Your z is negative, try setting it to 0
now its visible but its really small like 100 times smaller then its in the scene
that tiny white thing is the knob. Its not only a lot smaller it also isnt at the right position
Whats your other sprites z?
is it possible to make a tilemap with stuff like grass that sticks out
@craggy kite 1
Well I guess, the sprite of the box is just a smaller one than the knob, this is usually being used in the UI for the slider for example, which is tiny. So you should not worry about that until you got your own graphics in, tbh. @fringe jay
but the knob is smaller than it is actually
Uhh
so
I kinda need help
xD
so I am trying to make a top down shooter right?
so, I made individual sprites for the player holding the gun or knife or whatever
How am I able to pickup a knife or gun and then change my players sprite to the right one with the correct gun/weapon feature?
@frail dew there are 2 ways to change sprite do it manual at picki'up/swap weapons by script
or use Animator to change sprite/animation depend of parameters u give him by script
@open depot could you help me out in dms?
Welp im newbie too ๐ but maybe that gona help u a bit https://www.youtube.com/watch?v=Vfq13LRggwk&list=PL4vbr3u7UKWp0iM1WIfRjCDTI03u43Zfu&index=4&ab_channel=MisterTaftCreates
Welcome! Today we're going to set up a 4 way animation system, similar to the movement found in traditional JRPGs, and top down action RPGs. Enjoy!
Tiled: https://thorbjorn.itch.io/tiled
Tiled2Unity: http://www.seanba.com/tiled2unity
Art Assets: https://opengameart.org/content/zelda-like-tilesets-and-sprites
Unity: http://unity3d.com
Abou...
but instead of create movement animations make weapon change
Ideally. the gun should be a seperate sprite from the player
and you just enable/disable that sprite if you have, or not have the gun
Yes, absolutely. You can put the grass on a separate Tilemap Renderer object to avoid making the grass collide when using a Tilemap Collider 2D
I need helparu, currently I am doing a testing project to learn what I can about unity. I'm doing the 2d player animation, I have horizontal movement down but vertical is weird. idk how to animate the player based of a launch and when its falling. also when I am moving right in mid air it is battling for control on the animation
I currently have to press and hold "S" to get the falling animation since I am using a GetAxis("Vertical")
Select your object to be able to see the animator transitions at runtime.@nimble crescent
how can i implement a filling tool like the filling bucket in photoshop/gimp?
i'm doing a drawing game with SetPixels() on a texture
@real pilot look up flood fill algorithms. Might even find some c# code.
yea doing that right now, thank you ๐
Yo bois how can i access light2D intensity from another script :p
Is there a way I can get my enemy sprite to face in the direction of my player. So far I've used MoveTowards() to get it to follow the player which works great, but it only faces the one direction and that's away from the player sometimes.
You can make a function that flips the transform by 180 degrees on the Y axis when the enemy's movement vector is negative (or positive, depending on which way it starts)
You'll have to make a reference to the light, i.e.
public Light2D light;
Then drag the light into the slot in the inspector
Then access its intensity value in the code
light.Intensity = 5
hello, can someone tell me when OnTriggerEnter2D and Exit2D would be called when game starts? I have some auto detection that works on runtime but doesn't affects when gameobjects are already in level.
yeah, I found a workaround. No need for an answer
how do i turn slides off
so my character stops sliding when i realase a button or the d button
use GetAxisRaw instead of GetAxis
if you're changing the velocity based on the movement from GetAxis, then yeah, do raw
my game is a 2d top down pokemon like game using wasd controls and all i have so far is simple left and right movement on my top down gameplay, could someone send me a file for a good 2d top down character controller? if so then ping me.
why does my char fall through the ground?
the ground is a tileset
the char has a box collider and a rigidbody2d
is the interita value in rigidbodies like velocity but for spinning?
do colliders that are disabled still trigger ontriggerenter2d?
Add a boxcollider2D instead
3d colliders dont work well with 3d
Did you add a collider to the tilemap too?
Is there a way to edit the spline of a sprite shape through code?
Basically i want to make a floor like hill climb racing
and make it random with code
There definitely is; I'm no expert on the subject but this video talks about it briefly https://youtu.be/Z_FaqmP5Wm0?t=144
In this episode of the Prototype Series - we try to take Unity's latest 2D demo and implement new magical game mechanics to it! โจ โ๏ธ
โญ Download the project here: https://on.unity.com/2GfTPqP
โญ Check out our longer training session! https://on.unity.com/3ieU81R
โญ You can find the original Lost Crypt demo here: https://on.unity.com/33g9jUn
ty ๐
Np. he starts talking about it at 2:24
oh the only reason i didn't find the SpriteShapeController is because i didn't imported the U2D namespace
So, I was trying to make a 2D cutscene using Timeline. The cutscene plays just fine after starting the scene from Unity or even if you press the start button on the menu. However, if you load the cutscene, start the GAME scene, return to menu and click on ''Start game'' again, it doesn't play. Why would that be?
if you are using static field make sure scripts arent loaded twice when you come back to main menu
create an array of all your name, shuffle it, take the first ;p
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class namegenerator : MonoBehaviour
{
public TextMeshPro Text;
public void BtnAction()
{
PickRandomFromList();
}
// Start is called before the first frame update
private void PickRandomFromList()
{
string[] students = new string[] {"stijn", "joris", "hakan", "anthony", "poeki", "audrey" ,"baris" ,"natalia" ,"nataniel", "melanie", "asan", "mootje", "izzet", "marvianella", "saoussane", "rumesa","abubakar"};
string randomName = students[Random.Range(0, students.Length)];
Text.text = randomName;
}
}
its not working
Can you elaborate it better please?
I'm really a beginner, so sorry for any trouble
if you load a scene with a script that use singleton and you didnt disable it, it will reload again, having twice the script running, which can break stuff
what is not working artem
make sure button is linked, that code should work, add debug.log in it to make sure it goes trought
the only code in the cutscene is this one, is this a problem?
no
It executes after the last frame
the code in the main menu is probably the problem
Hmmm I get it, thank you. One last thing, where in the preload scene do i put the script?
making sure the script is destroy on awake
no idea what is your project or how its build i cant tell
I don't know why but my character can jump more than once while in the background and all because I did the colider, does anyone help?
Hello, what should i do to create a 'spawn area' for my object? I want the objects to be spawned in random position but only on the green area, not the red one.
@lusty salmon I recommend doing it by imagining the red part doesn't exist for each axis, so generate a random number between 0 and 2 * the band width for each axis, then add the size of the red area on the given axis if it's greater than the width of the band (but only if the corresponding opposite axis is > the band size, and < the total width - the band size)
As for the unity part, I can't help with that
sorry, but i dont think i quite understand about what you said there. ๐
Actually it turns out it doesn't work anyway, my bad, give me a moment
so, basically i need to add several ifs statement?
oh, okay
actually, i just found out this forum asking similar problem, i'll try this and i will update it soon :)
https://forum.unity.com/threads/spawn-object-in-certain-zone-2d.930684/
@lusty salmon Generate Y coordinate 0 - 560, if it's between [0 and band width] or [560-band width and 560], then generate a random X across the full width (because the x is always in the green in the green here), otherwise, generate a random value between [0 and 2*band width] and add the red width if it's greater than the band width.
A tutorial might be better to follow, but the method here should work if you get stuck
i'll try these two solutions and see which one is easier/perform better. thank you for your time ๐
@lusty salmon
oh wow, is it more simpler that way.
but another problem(?), does this work on devices with different screen size? I know i shouldn't hard-coded the size of G.
Finally finished with spawn area, in my opinion using polygoncollider works like a charm
@lusty salmon That's good, I realised last night that my answer would be biased towards the middle, woops
Now my goal is to make those enemies shoot a bullet towards the player. ๐
One step closer to finish ๐
Can anyone help me with my 2d car? i finished it but there is a wheel joint bug
Does anyone have any experience with wheel joind 2d? i am using them, but i get this weird effect. on the right side you can see the parameters
so aparently the wheel joints are supposed to be attached to the carbody instead of the wheels
guys
Anyone know why Physics.OverlapSphere is not working
if (Physics.OverlapSphere(groundCheck.position, 0.1f, groundLayer).Length > 0)
Here is the groundcheck
It has ground layer
And is set to ground
I told it to log the count of the ones found and I get
@uneven rune https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html for the 2d colliders
oh
i want my code to reset the scene when i collide with another object
but it wont work
I would add a debug.log at each step to see which one doesn't work
It might also be better to check the tag rather than name
@uneven rune OverlapCircleAll
thanks
its because of compression
i think
but idk how to get rid of it
something with exporting the image
im making a platformer and i want to see in the editor where my character was like a trial time ghost thing
dont need actual functionality for it ingame
just to see how to setup objects relative to the movement
trying to get player movement set up what is wrong with this code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody2D myRigidbody;
privte Vector2 change;
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
change = Vector2.zero;
change.x = Input.GetAxis("Horizontal");
change.y = Input.GetAxis("Vertical");
Debug.Log(change);
}
}
What's it doing? Does it not compile? Does it not behave as expected? If so, how?
it says error cs1002
Sounds like it's not compiling, it doesn't give any more than that in the console?
error cs1519
It usually tells, for compile errors, what line and character caused the issue
;
It's not always 100% correct, but it's usually helpful
There
You have "privte Vector2 change"
I think that typo might be the issue
ok no more errors
Also, I don't think you actually need to declare them as "private"
Though there's nothing wrong with doing so
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal");
change.y = Input.GetAxisRaw("Vertical");
if(change != Vector3.zero);
{
MoveCharacter();
animator.SetFloat("moveX", change.x);
animator.SetFlaot("moveY", change.y);
}
}
void MoveCharacter()
{
myRigidbody.MovePosition(
transform.position + change * speed * Time.deltaTime
);
}
}
is there any spelling errors?
or anything wrong with it
I was right
its always a mis-spell
:p
It should tell you thats an error though
since Animator won't have a function called SetFlaot
๐ค
thanks
Sweet
But you said there were no mor eerrors
before i corrected it
I'm confused
I said yes first lol
it told me there was an error so i asked discord and u told me the mis-spell then i corrected it no more errors
Inari is just giving me a hard time cause I said I was right
but
it should ilke highlight the line
with red squiggles
So you'd know it's that line
Ohh
I use notpad

Krugg smash
Well still, the error will have like
At least use notepad++
i use notpad on a windows 8.1
its not going to tell me if there is a error in my spelling
Kk
Have fun with that
Wiht the line number
In the meantime, I have no further intention of being your notepad spell check plugin
Peace
/giphy //
can anyone help me with this two problem
so i have a puzzle game thats connected to sensor using arduino and it works sometimes but on the other its just lags , i dunno what to do to refresh that specific function so that puzzle pieces lights up
and the second problem is im trying to add audio to puzzle like piano tiles (i have 16 pieces in the puzzle) the idea is that i group the first four puzzle in the array and once one of the pieces is called the a note plays but i dont know how to make it so (if anyone is willing to show the way )
I'm assuming this isn't a code question and should be asked elsewhere. If it's Unity related, post it in #๐ปโunity-talk else in #497872469911404564.
it is a code qn
im looking for a code that refreshes a specific function in the code if it takes too long and another code that can activate a function when a attribute from a array is called
Is this related to Unity?
Is this code portion related to Unity?
wdym?
Some folks come in here and say they are working on a Unity project then ask code completely irrelevant to Unity API
code snippet can be posted with back ticks if necessary, else you can post it at hatebin or other code services if too long; such as hatebin.
You should post your actual problem and code. If it's a beginner question, go ahead and post it here.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO.Ports;
using System.Threading;
[RequireComponent(typeof(AudioSource))]
public class Puzzle : MonoBehaviour
{
public string piecestatus = "idle";
public Image A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4;
public Image A11,A21,A31,A41,B11,B21,B31,B41,C11,C21,C31,C41,D11,D21,D31,D41;
public Image[] pieces = new Image[16];
public Image Selected;
public string COM;
public Transform edgeParticles;
public int hello = 0;
public KeyCode placePiece;
private SerialPort serialPort;
private bool serialOK = false;
public string checkPlacement = "";
public AudioSource audioSource;
public AudioClip CorrectS;
public float volume = 1.0f;
public Text textBox;
public float timer = 0f;
bool Increasetime = true ;
// Start is called before the first frame update
void Start()
{
serialPort = new SerialPort(COM , 9600, Parity.None, 8, StopBits.One);
try
{
serialPort.RtsEnable = true;
serialPort.Open();
serialOK = true;
Debug.Log("Serial OK");
}
catch (Exception)
{
Debug.LogError("Failed to open serial port for circuit");
}
audioSource = GetComponent<AudioSource>();
//Randomer();
}```
sorry its morethan 2000 characters
gimme a sec
Unity is single threaded so unless you've got some threaded operation that is listening to another thread then it isn't likely easy.
You could use a coroutine to continuously repeat and wait for an operation but I don't think that's what you're asking for.
{
string dataString = serialPort.ReadLine();
var dataBlocks = dataString.Split(',');
if (dataBlocks.Length < 8)
{
Debug.LogWarning("Invalid data received");
return;
}
int AState, BState, CState, DState, EState, FState, GState, HState;
if (!int.TryParse(dataBlocks[0], out AState))
{
Debug.LogWarning("Failed to parse AState. RawData: " + dataBlocks[0]);
return;
}
if (!int.TryParse(dataBlocks[1], out BState))
{
Debug.LogWarning("Failed to parse BState. RawData: " + dataBlocks[1]);
return;
}
if (!int.TryParse(dataBlocks[2], out CState))
{
Debug.LogWarning("Failed to parse CState. RawData: " + dataBlocks[2]);
return;
}
if (!int.TryParse(dataBlocks[3], out DState))
{
Debug.LogWarning("Failed to parse DState. RawData: " + dataBlocks[3]);
return;
}
if (!int.TryParse(dataBlocks[4], out EState))
{
Debug.LogWarning("Failed to parse EState. RawData: " + dataBlocks[4]);
return;
}
if (!int.TryParse(dataBlocks[5], out FState))
{
Debug.LogWarning("Failed to parse FState. RawData: " + dataBlocks[5]);
return;
}
if (!int.TryParse(dataBlocks[6], out GState))
{
Debug.LogWarning("Failed to parse GState. RawData: " + dataBlocks[6]);
return;
}
if (!int.TryParse(dataBlocks[7], out HState))
{
Debug.LogWarning("Failed to parse HState. RawData: " + dataBlocks[7]);
return;
}
Debug.Log(dataString);```
{
if (serialPort.IsOpen == false)
{
serialPort.Open();
}
if ( A1.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) && A2.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) &&
A4.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) && A4.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1)){
serialPort.Write("1");
serialPort.Write("5");
}
if(hello == 0 ){
if(a == 1 && g == 0){
A1.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
//Instantiate(edgeParticles , C1.transform.position, edgeParticles.rotation);
A11.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
}
if(b == 1 && h == 0){
A2.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
//Instantiate(edgeParticles , C2.transform.position, edgeParticles.rotation);
A21.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
}
if(c == 1 && e == 0){
A3.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
//Instantiate(edgeParticles , C3.transform.position, edgeParticles.rotation);
A31.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
}
if(d == 1 && f == 0){
A4.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
//Instantiate(edgeParticles , C4.transform.position, edgeParticles.rotation);
A41.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
}
}```
i did this part for each row for the puzzle
{
if (serialPort.IsOpen == false)
{
serialPort.Open();
}
pieces[0] = A1;
pieces[1] = A2;
pieces[2] = A3;
pieces[3] = A4;
pieces[4] = B1;
pieces[5] = B2;
pieces[6] = B3;
pieces[7] = B4;
pieces[8] = C1;
pieces[9] = C2;
pieces[10] = C3;
pieces[11] = C4;
pieces[12] = D1;
pieces[13] = D2;
pieces[14] = D3;
pieces[15] = D4;
Selected = pieces[UnityEngine.Random.Range(0,pieces.Length)];
Selected.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
Debug.Log(Selected);
if(Selected == A1 || Selected == A2 || Selected == A3 || Selected == A4){
serialPort.Write("1");
serialPort.Write("5");
}
if(Selected == B1 || Selected == B2 || Selected == B3 || Selected == B4){
serialPort.Write("2");
serialPort.Write("6");
}
if(Selected == C1 || Selected == C2 || Selected == C3 || Selected == C4){
serialPort.Write("3");
serialPort.Write("6");
}
if(Selected == D1 || Selected == D2 || Selected == D3 || Selected == D4){
serialPort.Write("4");
serialPort.Write("8");
}
if(Selected == A1 || Selected == B1 || Selected == C1 || Selected == D1){
}
}```
if(Selected == A1 || Selected == B1 || Selected == C1 || Selected == D1){
if(e == 1){
StartCoroutine(waitThreeSeconds());
//Randomer();
}
}
if(Selected == A2 || Selected == B2 || Selected == C2 || Selected == D2){
if(f == 1){
StartCoroutine(waitThreeSeconds());
//Randomer();
}
}
if(Selected == A3 || Selected == B3 || Selected == C3 || Selected == D3){
if(g == 1){
StartCoroutine(waitThreeSeconds());
//Randomer();
}
}
if(Selected == A4 || Selected == B4 || Selected == C4 || Selected == D4){
if(h == 1){
StartCoroutine(waitThreeSeconds());
//Randomer();
}
}
}
IEnumerator waitThreeA(){
//hello = false;
yield return new WaitForSeconds(3);
//print("A");
hello = 1;
}
IEnumerator waitThreeB(){
//hello = false;
yield return new WaitForSeconds(3);
//print("B");
hello = 2;
;
}
IEnumerator waitThreeC(){
//hello = false;
yield return new WaitForSeconds(3);
//print("C");
hello = 3;
}
IEnumerator waitThreeSeconds(){
//hello = false;
yield return new WaitForSeconds(3);
print("BOOOM");
//hello = 1;```
i did use coroutine but its still lags
string dataString = serialPort.ReadLine();
var dataBlocks = dataString.Split(',');
int state;
if (dataBlocks.Length < 8)
{
Debug.LogWarning("Invalid data received");
return;
}
for(int i = 0; i < dataBlocks.Length; ++i)
{
if (!int.TryParse(dataBlocks[i], out state))
{
Debug.LogWarning($"Failed to parse state[{i}]. RawData: {dataBlocks[i]}");
return;
}
}
Debug.Log(dataString);
```Edited: Updated
Post the code at hate bin if too long please; a moderator would normally be the one telling you this. <#๐ปโcode-beginner message>
Not entirely sure if it can supplement but definitely an optimization improvement over what you had before.
ok thank u
I've got to go though, good luck.
Holy lack of pastebin, batman!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal");
change.y = Input.GetAxisRaw("Vertical");
UpdateAnimationAndMove();
}
void UpdateAnimationAndMove()
{
if(change != Vector3.zero);
{
MoveCharacter();
animator.SetFloat("moveX", change.x);
animator.SetFloat("moveY", change.y);
animator.SetBool("moving", true);
}
else
{
animator.SetBool("moving", false);
}
}
void MoveCharacter()
{
myRigidbody.MovePosition(
transform.position + change * speed * Time.deltaTime
);
}
}
what is wrong with this code
ive downloaded a new coding app to help me figure it out but its not working
@tawdry hornet In the case of moving character I always use
transform.position += change * speed * Time.deltaTime
or
transform.position -= change * speed * TIme.deltaTime
I or big youtuber (as I saw) not use rigidbody.MovePosition
there is a error telling me there is something wrong with a }
@tawdry hornet you write a ";" after an if in UpdateAnimatorAndMove()
remove this ";"
if(change != 0);
should not a ";"
@tawdry hornet
o
now there is 2 errors
what are they saying
ok 1 sec
ok cool it works now
wait
1 problem acctullaly
my walk movements dont work
i think thats somthing with my animator
tho
I'm trying to reset the scene whenever i collide with the enemy, i made sure to tag the enemies and the player, but even so, the scene does not reset when i collide with the enemy.. i have also tried to use the Enter method but it gives me a red error saying something about permeators or something
@raven badge can you copy the code please?
np, feel free to ask for help tho
I want to get the sprite of the tile that my ray has collided with and I currently have this code;
RaycastHit2D hit = Physics2D.Raycast(Aim.position, Aim.up, reach, blockMask);
if (hit.collider != null)
{
sr.sprite = collided tiles sprite;
}
but I doubt if that is possible with this code
if not is there any other way I could get the Tile I've collided with?
or should I use game objects and get their sprite instead
hit.collider.gameObject.GetComponent<SpriteRenderer>().sprite
oh u said tile
idk much about 2d tbh
but if it were gameobjects, it would be easy
Why do I get an error in this? everything in Unity matches up. I am making a ground check for jumping I put error to show it does't have the *s
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class groundcheck : MonoBehaviour
{
GameObject player;
// Start is called before the first frame update
void Start()
{
player = gameObject.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Ground")
{
** player.GetComponent<playermovement>.isGrounded = true;**
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag == "Ground")
{ **player.GetComponent<playermovement>.isGrounded = false;** }
}
}
thx
Hey everyone! How can I make a "Rain" of objects? For example there is an infinite spawn of bullets on the sky above you. The objects "bullets" will be falling in a specific velocity. And when they are not visible just deactivate/destroy them. Ping me if there's some tutorial that can help me ๐
Have a look at the conventions for Type and Method naming ... it will save you ( and reviewers ) a lot of grief in the future.
anyone know of a way to get a 2d character to collide with 3d objects in a perspective view (not 2d)
3d collider..
Heyo!
https://www.codepile.net/pile/7AkLZ6GX
I got an issue I'd like to somehow fix x_x
I'm trying to reset the puzzle input completely so the user has to click the 3 correct objects all over again after clicking the incorrect one, any ideas?
{{ description }}
Make an array for your correct answers, and then make a progress integer (start at 0, if they get one correct, increment it by one)
Then all you need to do is check if their input matches the result in the array at the progress index
private int samples[] = new int[] {0, 3, 5};
private int progress = 0;
public void SamplesCheck(int nr)
{
if (nr == samples[progress])
{
//Advance progress
progress ++;
}
else
{
//Reset progress
progress = 0;
}
}
Unless you need booleans for a specific reason, this is a much simpler way to do it
Then check if the progress integer is high enough to open the door
i can't understand why my character moves faster diagonally, how is that happening?
moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * speed;
rb.MovePosition (rb.position + moveVelocity * Time.fixedDeltaTime);```
Ah something I can actually help with. When you apply forces in both directions, the resulting force is larger than if you applied it only one direction.
If you draw a triangle where both sides are 1, what is the value of the diagonal?
sqrt(2) which is > 1.
The result is that when you move diagonally, you move faster due to the magnitude of the combined forces.
@wooden acorn
Oooh i understand it now
i need to normalize it, right?
i normalized and it worked, thank you so much!
c:
Yep!
Why doesn't this work
I want my monster to die if its z rotation is 180, (if hes on his head)
I dont get any errors it just doesnt work
it has to be 180 flush, no floating numbers
also, remember that Rotation is not a Vector3
can someone tell me how i made a object ALLWAYS point towards anothe in a top-down perspective?
(C#)
can any one help with my main menu? When ever i hit PLAY it acts like its about to switch a scene but it doesn't.
it just does this
nvm i got it
Anyone experienced with Unity able to help me make pixel art show up properly?
Do you load a scene somewhere in a script?
i just needed to fix the script thx tho @civic knot
oh and thx for sending me the link for the beginner guide for unity.
it is easy make a scene and build it in the setting
u need to build settings accoring toyour order
Does anyone know if it's possible to tie a sound file to a specific type of tile in tilemaps?
Never mind, I figured it out
import spritesheet, remove compression, change filter type to "point (no filter)", change the pixels per unit, change from single to multiple, open the sprite editor, cut it as you like and you're good to go
@lilac tangle bruh thats a lot of if statements, also hard to read what your trying to do
your veribles make no sence its gunna take up a bunch of memory
can seperate bits in to
methods or use return types to simplify what ever it is your trying to do try not to use so many if statements
....
i say if a script causes you to lag theres a better way to do it
try not to leave debug statements or exceptions in your scripts
cache the sprite renderer instead of getting objects component each time
nvm bru
id be here for ages....
why dose checker have so many perams..
a b c d e f g says nothing of what it dose
i finished a UI game and the canvas size is 4:3 and its all working and stuff but when i build the game, the text doesnt show up. help?
check order of gameobjects i think it renders it based of priority top most important bottom least if not try other way round
think like photoshop layers
oh worked ty
is there a built in way to set up animations with multiple orientations depending on a condition? Like I've been using the animator flow chart, but it seems unintuitive to have to have a block for every different angle for every cycle, and have them all connect depending on conditionals
you doing a top-down game?
cant really have more than 2 orientations in a platformer... just guessing
have a look at blend trees
not sure thats what you mean but it cleans up the grapth a bit..
i think 2d freeform on blendtree is what you mean you can set multiple clips in run from the single blend tree set it to blend between animations based on the slider value
iv its pritty easy to setup 2dfreeform with a controller...
image from docs
not sure tho...
yeah I am
it's for the main player
I have 4 different orientations each with their own animations
I'll take a look
I'm now using a blend tree
but the problem is that I have multiple idle orientations
how can I change which idle orientation is used depending on the blend tree direction it came from? (e.g walk left > idle left)
here are the params I'm using btw for walking orientation
I'm trying to do a vision cone with a custom mesh and Raycast but when i call the code to set the origin to the enemy position in the update of the enemy it doesn't work. Does anyone know how i could try and fix it? If i move the origin by a vector with the x and/or y increasing by 1 it works.
Me and my friend are trying to make an minecart type game using splines. We have run into issue with our current asset and was wondering if anyone knew a better one. We were pairing our spline asset with the sprite shape renderer/controller to generate the track, but I think there is just to much different between the asset and how the sprite renderer handles points. Is there an asset out there that does both what the sprite render does and has script that handle the following/rotation?
can someone tell me how i made a object ALLWAYS point towards anothe in a top-down perspective?
(C# unity)
I'm trying to do a vision cone with a custom mesh and Raycast but when i call the code to set the origin to the enemy position in the update of the enemy it doesn't work. Does anyone know how i could try and fix it? If i move the origin by a vector with the x and/or y increasing by 1 it works.
i'm doing a top down 2D game - how should I handle layering so that objects an object higher on the screen than another appears above it, while an object lower than another appears below?
what I tried was setting the z of the object to the y level, though since the camera follows an object it doesn't work
Not quite clear what you're doing. Maybe record a video demonstrating the problem and share your code..?
how can I tint my sprite white?
SpriteRenderer.color = Color.White or something.
How do I properly code changing music when I enter a certain zone on the map? Currently I have a composite collider tied to a tilemap and when I enter/stay in it - the music changes and then resets to default when I leave. However for some reason it keeps changing between two tracks while I'm still inside the collider?
This is the audio manager code: https://hatebin.com/aqoidqpwnq
This is the music switcher code: https://hatebin.com/vinhyikyty
This is one composite collider I can stay inside and the music should be the same when I'm inside, but it keeps switching back and forth if I move
Any ideas? .-.
OnTriggerStay is triggered once per physics update. If you only want it to change once you should probably use OnTriggerEnter
Yeah, I tried that - didn't work
We figured out that it was a problem with composite collider - somehow it only worked when I was standing exactly on the border of it. If I left the border - it was as if I left the whole collider, the concept of inside/outside didn't exist. I switched it off and everything worked perfectly fine.
So, I have a script to hold a object
An I am trying to make it so that it grabbs it from where you click
So far the results have been
not the greatest
Does anyone have an idea as how to do it?
I think i know a way...
i need to get a position, and fix the rotation
So how can I get a position with the rotation undone
if I can get that i can just do the rotation multiplied by the offset to get it
So main question:
How to get a position, and remove the rotation from it?
so close to getting it aarg
I am using very sus code
It be so close
so close to correctly grabbing it
nooo it deleted my gif
Here is the not gif version
I am free
not sus code
hey! how would i go about calculating a recttransform's position with another anchor, like unity editor does automatically when you change the anchor?
how can i detect in another script if that collider of that prefab hitted something
Hi ! I am currently testing addressables, I was wondering if it is respecting playersettings > quality > Texture Quality, when building the bundle for a specific platform or if it is copying the file depending on the max size in the texture properties. Did not find a way to inspect the bundle, so not sure of the result
Anyone know how I can get 2d pixel art to show up without imperfections? I've gotten close but there always seems to be imperfections in the art.
I'm trying to get the art in Unity to showup exactly how it does in paint but can't seem to get rid of thee black dots and line imperfections.
2d-code, uhm, well, i would need some help.
I have a "working" chunk system, and they can be loaded, and now im working on the onload functions, and yeah:
foreach (int i in WorldChunks) {
if (i == 1 && Vector2Int.Distance(new Vector2Int(PlayerChunkX,PlayerChunkY), i need the coords of i here) >= SettingChunkUnloadDistance) {
UnloadChunk(THE COORD.X of i, THE COORD.Y of i);
}
}
WorldChunks is a 2D array, and a "coordinate" could be either 0 (unloaded) or 1 (loaded);
PlayerChunkX and PlayerChunky is a coord in the WorldChunks array;
i found out that a foreach can be used to find every "chunk that is loaded" aka a 1, but uhhh
in that code snippet i basically just wrote in what i would like to ask for help how to get. the coords of "i"
yeah im not a pro tbh, i can get stuck very often because of my lack of knowledge
@icy agate Pixel art has to be pixel perfect for the orthographic camera correct size for the current resolution. There's pixel perfect package in the manager for that and/or research pixel perfect implementations.
I am making a digital board game in which the 4 players around the board have hands of cards. I would like it so that, if a player has an empty hand, the camera will dynamically zoom in, as the extra space for the hand is no longer needed. I have taken some screenshots of this.
As you can see in the second image, the bottom player no longer has any cards. As you can see in the third image, I have drawn a red rectangle around where the camera should be as a result of this.
What would be the best way to accomplish this? I think it might have something to do with the camera "clamping" feature, but not sure.
Complicating the matter further is that I want the camera to also rotate depending on which player's turn it is (so that whoevers turn it is always has their hand at the bottom of the screen). This results in a lot of permutations of possible camera rotations, positions, and zoom level.
Basically, I would like to be able to set 4 values (the edges of a bounding rectangle) and have the camera always adjust to those bounds.
Hey guys I wanna know if anyone of you can help me in something. I want to make my character move it's face towards the mouse, I can't figure out how to do it. I can attach images if you don't understan what I mean
So, you want to rotate a 2d character towards the mouse
that's a common question
if only I was good at math, then I would be able to remember off the top of my head
the solution involves using Atan
ok, there we go
atan2(y, x) gives you the angle in radians
then * Mathf.Rad2Deg converts it to degrees
@slate epoch
I'm sorry for answering late
Ty for your answer but that's not what i meant. I know it's a little confusing tho.
Is like I want to make a sprite orbitate a point, but the sprite not changing it's rotation
this might be an example
like the earth "sprite" is not rotating, but the object is orbiting
sorry for the mess ๐
Guys I have a problem