#๐ผ๏ธโ2d-tools
1 messages ยท Page 46 of 1
ok
so in your case when you press space
but how do i put it in the code?
hello, so the combat in my game is melee, and i want to have my script check for enemies entering the sword hitbox as long as the animation is playing (because my melee is a dash attack, i sometimes will dash into an enemy mid swing) but i run into the problem that damage and knockback gets applied once per frame, since its checking as long as the animation is playing. is there a way that once i apply damage to an enemy, i cannot apply any more damage until the animation ends / i swing again?
here is the important code:
void Update()
{
if ((this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash")) || (this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash2")) || (this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash3")))
{
Attack();
}
}
void Attack()
{
// Detect enemies in range of attack
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(SwordHitbox.position, attackRange, enemyLayers);
// Apply "damage" to enemy(s)
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<slimeHP>().TakeDamage(attackDamage);
}
}
but how do i put it in the code?
if (Input.GetButtonDown("Jump") && isGrounded == true && (animator.GetBool("playerDead") == false))
{
Jump();
}
the function:
void Jump()
{
isGrounded = false;
animator.SetBool("isJumping", true);
animator.SetBool("isCrouching", false);
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
if(animator.GetBool("shiftHeld") == true)
{
moveSpeed = 3f;
}
else
{
moveSpeed = 2;
}
}
some of that is unneeded, but just to give you an idea
thats the code for my game
so replace it?
use the input.getbuttondown for whatever key you use for jump, and in the function, use animator.SetBool("isJumping", true)
theres a video that brackeys made on it
i used it, and it does not work
what part doesnt work
I think the problem with his animation kit
if i remember correctly it doesnt have a "Freefall" jump state
Whereas, in brackeys video it does right?
make sure "loop time" is turned off for your jump animation in the inspector, you also need a script to check when your character is on the ground, to cancel the jump animation
is their a vc channel I can show you this in
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
this is how you make him jump
loop time is off
you have no exit condition for jump in your animator
how do I set that up
do you have a script that checks if you are on the ground
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.
@bronze sundial any ideas?
inside the animator tab, right click on jump and make a transition from jump to idle / walking
and the transition condition from jump to idle / walk should be "isGrounded == true". you may need to make a new parameter and set it to true / false in your code
when jumping, isGrounded == false. when not jumping, isGrounded == true
he has that already with the "isJumping bool"
this is how it looks now
@bronze sundial any ideas?
https://www.youtube.com/watch?v=L6Q6VHueWnU&t=17s&ab_channel=KyleSuchar watch this, im a bit busy
Add 2d player movement and jumping in Unity! The code will also check for the ground so the player can not endlessly jump!
Instagram: https://www.instagram.com/717games/
DOWNLOAD UNITY ENGINE: https://unity3d.com/
skip to 4:19 for jump
@bronze sundial where in my code should I add this?
@bronze sundial where in my code should I add all of this?
Hey all
I've been trying out bolt and i have ran into a problem with my player movement. that being he doesn't move
I believe it has to do with the velocity application part.
You're not setting the rigidbody's velocity anywhere
you're calling GetPointVelocity at the end which... is probably not what you want
ah I see
wow it was really simple
I just typed in the wrong thing
thanks for the help
i'm trying to use a overlapcircle to check if the player is touching the ground, but it never returns true, what am i doing wrong?, the groundLayer is a layermask and is declared above, and set in the engine
bool grounded = Physics2D.OverlapCircle(playerpos, 1, groundLayer);
//handle gravity
if (grounded)
{
UnityEngine.Debug.Log("Touching");
}
please @ me
the code looks fine
it would come down to the rest:
- where
playerPosis - what
groundLayeris set to - what layers everything is on
the player is on it's own layer, and the ground layer is set to 3
show the inspector for your script where you'ver configured the groundLayer mask?
ok, one second please
the code for making the layermask is
public LayerMask groundLayer;
yeah they are
then the last thing to check is - how you are assigning playerpos
Are you giving that any value in your script at any point?
yeah
it's in a vector2,
and i forgot to assign it
wow
thanks
ok, it's still not working: playerpos = player.position, @ me
i gtg, thanks
is it possible to use a tilemap as spritemask?
Sure, you can put any components on a tilemap
hi all, how do you change the size of an orthographic camera? I have a canvas which uses screen space-camera as it's render capture mode
for some reason the addforce command isnt doing anything
the top print reads "(-2.1, 4.6)", while the bottom print prints "(0.0, 0.0)"
the object isnt colliding or touching anything
Is there a way I can make a collision box that has holes in it where certain objects are
is the rigidbody kinematic?
no, dynamic
is Time.timeScale set to 0?
it shouldnt be, ive never touched that
also everything else around it moves just fine
that's a pretty small force
try printing:
print(sawbladeRB.velocity.ToString("F8"));
it could just be a very small velocity
If this is like a "one-off" force, launching the sawblade out of a gun or something, you should generally use ForceMode2D.Impulse or ForceMode2D.VelocityChange
that line of print read "(0.00000000, 0.00000000)"
and ill try with impulse
attaching the impulse parameter to the addforce didnt do anything. right now with testing, im having the sawblade spawn 5 units to the right of the launcher so that it isnt touching anything
and visual studios telling me that ForceMode2D doesnt contain a definition for VelocityChange
if it's actually 0 like that then something is going on like it's kinematic
ah yeah I always forget that 2D only has Force and Impulse
hmm, well it reads dynamic in the inspector, and none of its parents have rigidbodies
Try printing:
print($"body type: {sawbladeRB.bodyType.ToString()} isKinematic: {sawbladeRB.isKinematic}");```
(note there's a separate IsKinematic field that is not the bodyType field)
also check the constraints - is the position frozen?
also the Simulated field
im not sure i understand, its saying rigidbody2d doesnt contain a definition for "isKinematic"
and no, no constraints, and yes it is simulated
shoot, ill try to fix that, but i have to go right now. ill work on it once im back home, thanks for you help preator.
2d-code, maybe you can help me!
im making a 2d rts game and I want some of my tiles to be resource tiles, ala red alert, where you can path over them but a collector unit can gather it.
Whats an efficent way for the collector to tell which tiles are resources vs just any other tile?
How can I change the sprite size in my script?
How to do this in Unity2D?
hey
i have a rectangle and a square... the rect triggers collision with the square.
but when i slid the square to the rect sideways, it doesnt trigger
but when the square is dropped on the rect it triggers
@nimble zenith Don't crosspost.
ah very sorry
um so I can't find the setting that actually changes how far zoomed in the camera is
size? i think that's it
doesn't actually change it when I play it
what's the code you're using?
not doing it in code, just doing it manually
okay, and when you change the "size" property, it doesnt change how your game looks, at all?
it does for me.. can you take a video of your game view when you're changing the size?
weird. this is how it is for me
Hi guys ๐ I am looking today to try and get a sprite to move across the screen. I would like a sprite to travel from one tile coordinate to another tiles coordinates, and Ideally I would like to draw a line between the two points.
Would anyone be able to give me any pointers here, if there is something I should be using to animate the sprite that will travel, or even simply how to draw a line between two points on a 2d map, that would be excellent.
I can see a basic way to get things done in my head, get coordinates and move sprite etc, but what with cinemachine and not knowing Unity well I thought I would ask around first
So you just want a sprite to go to 1 coordinate then to another? @upbeat sinew
like back and forth?
Hey guys. Old man here, trying to learn some new tricks and playing with Unity. I have made a prefab, "Player" and a prefab "Healthbar". My player script has a private Healthbar healthBar; serialized field. I have "dragged" my healthbar prefab into the player prefab in the unity ui. The player prefab is spawned by my network manager when I start my server. I have added code to my player script, that instatiates the healthbar when the player spawn. I have added a debug.log to my healthbar, and it appears to spawn. However, the healthbar is no where to be seen. Probably a vague question, but any ideas what I might be doing wrong? Or what info I can provide to better explain my problem? ๐
This is known as "masking", there's various ways to do it, between UI, Sprites and even Quads. Have a look at each of the various ways masking can be used in Unity, and read up on the pros and cons of each to find the one that's what you need.
Look in your scene, where is the healthbar positioned?
@abstract olive It looks like it's positioned above it's parent, then "stretched down"
@abstract olive I recreated the prefab. Now it looks like it's directly on its parent - just not visible! I see the border .. and the it looks MASSIVE.. but there is nothing inside the border.
Can you screenshot what you're seeing/doing?
@abstract olive https://prnt.sc/12xfzvb . I have spawned a Player object. When I spawn the player object, I instantiate a clone of Healthbar that I am planning on showing beneath my character. As you can see from the screenshot, the border of "Image" is the outmost part of my healthbar, whilst "Fill" is the inner part (a slider that I am adjusting to simulate hitpoints)
Bit hard to make out from the screenshot, but my character is under the circle, in the middle of the screen. So the healthbar is grossly over scaled at the moment.
Is this a screenspace canvas?
Yes
I was thinking that maybe it shouldn't be .. because I want to use the same bar for other elements in the game as well ..
Unless you're doing some world to screenspace conversions, the elements are not going to 'follow' a world object.
Try redoing it with a world space canvas, and treat it as a normal 3D object.
Can I update the existing prefab to use world space instead? And can I safely ignore the camera warning ?
World space canvas will use Camera.main aka FindObjectWithTag("MainCamera").GetComponent<Camera>() if you don't set anything
(e.g. if the warning is showing)
You can always pre-empt that by explicitly setting a camera for the canvas yourself
Like ... add a new camera, just for rendering the healthbar? (Sorry, the concept of cameras is new to me)
Anyway - changing it to world, it now appears to be position where I would expect it (crack in the middle of the parent), but I still can't see anything rendered. No graphics.
Could it simply be that going from a 250 px wide image to less than 32px is simply too small ??
If you're using a world space canvas, it shouldn't be resizing. ๐ค
If this is a 2D game, make sure the z-value is within the camera's view. Or if it's a child of the player, set it to 0.
I set the scale to make it fit my game. But maybe I shouldn't be doing that? Maybe all graphics should be the "correct size", since this is 2d only ?
(It is a child of player, and the z is set to 0)
Hey, is there a way getting a (isometric) tilemap as a 2D array?
Im trying to build a really basic ragdoll. I got all the hinge joints working, but when I move the player it does this...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private bool md;
// Start is called before the first frame update
void Start()
{
md = false;
}
// Update is called once per frame
void Update()
{
if(md){
Vector2 np = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = np;
}
}
void OnMouseDown(){
md = true;
}
void OnMouseUp(){
md = false;
}
really basic. I'm not sure what's going on
I'm trying to make it more like seen here
@mossy lantern how do I make the boy jump?
bruh

I attempted to use Vector2 lerp and movetowards, but that doesnt help either
@mossy lantern Don't spam this discord, you already have warnings against you.
Is that video from a tutorial or something? Can you not follow what they did?
that video is from my untiy
I found a video that does something similar, but mouse dragging in-game wasnt covered
I mean I can keep trying to find videos, just figured it'd be simpler to explain my exact concept on the Official Unity Discord server for tips
the first video is from in-game, where the second is me moving it in the scene editor
so im making a 2.5d game with a 2d sprite in a 3d world and i want to get him to jump but nothing i try is working, i only want him to go up on the y axis as its an infinite runner sort of game, any help?
bill, if it's a 3d world, don't you want to move him up and down on the z axis? (I'm a total beginner with Unity, so I'm just throwing this out there)
no you want to move on the y, z is forward and backwards
woka
this is me moving on the z then the y
Decide now if you intend to still be part of this Discord.
harsh
Fair question, there is no standard on Z or Y being up in a 3D space. But unity uses Y as the Vertical axis, and Z as the Depth Axis. I think this is to make it easier to switch between 3D and 2D spaces
Cheers for that - nice to know ๐
Assuming they have a rigidbody attached, you could look at constraining it to the X position
Or just use AddForce method to add force in the upwards direction
ive tried using addforce and it didnt work
what issues did you have?
yea, please show the script ๐
void Jump()
{
anim.SetBool("Jumping", true);
rb.AddForce(transform.up * jumpforce);
canjump = false;
}
the function gets called because the animation changes
jumpforce is set to 50 or something
one sec
so i changed it to
rb.AddForce(rb.transform.up * jumpforce, ForceMode.Impulse);
and it doesnt work still lol
Bruh I said Ok with a w
force is too low apparently
also make sure you're using FixedUpdate vs Update
private Rigidbody2D rb;
private bool jumping;
private float jf;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
jumping = false;
jf = 500.0f;
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump") && !jumping)
{
Debug.Log("Jump!");
jumping = true;
Jump();
}
}
void Jump()
{
rb.AddForce(transform.up * jf);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.name == "Floor")
{
jumping = false;
}
}
I was able to make mine jump on the Y axis using this
apparently Update is ok, just not recommended for reasons outside of my current knowledge lol
I put 2 emoji
i would standardize using GetKey and GetKeyDown in your code fyi, behavior is different especially since you're not setting any check for your jumps
Can you see what happens if you're on level ground?
when you are doing sudden force such as a jump, use AddForce(someForce, ForceMode.Impulse)
I'm wondering if you're getting a collision, but that'd be kinda fetched
(the forcemode part)
what do you mean see what happens when im on level ground?
instead of an incline
But try his method first
Otherwise I wonder if theres somethign about the animation? But I dont work with animators enough to help even diagnose if that's an issue
ive tried it without the aninamtion
and he is on flat ground, the camera just makes it look like an incline
no
also, you're using rigidbody on your player right? Not rigidbody2D?
ive changed to using rigidbody2d now as i thought it was becuase it was a 2d sprite
lol great timing
make sure the RigidBody in your code matches what you're actually using on the character
and there's no colliders above the character in anyway?
the code looks like it should give you vertical lift
yeah
I'd lower the 9999999 value in the inspector to 500 though
and the rigidbosy maches
for your script
gravity also doesnt effect it
anyone know why grid = FindObjectOfType(Grid); is giving me 'Grid is a type which is not valid in the given context'?
so thats something
not for this issue, just for easier to see
wait what? Your character doesnt naturally fall down?
no
Something is constraining your Y value
or RigidBody is not using it
can I see your components for the actor?
yea, you'll want 3D if you're landing on a 3D object or they wont collide as expected
even if it's a sprite it'd be fine
code for the basic jumping character
yeah, it works on that
ahhh
wait a min
one of my animations changes the y axis
wait a sec
oh and it works
just like magic
lol glad you got it homie
anyone know why grid = FindObjectOfType(Grid); is giving me 'Grid is a type which is not valid in the given context'?
FindObjectOfType<Grid>()
It was because Grid is a type, which wasn't valid in that context ๐
also tried grid = GameObject.Find("Grid");
but getting Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Grid'
Does the code I shared not work? @fickle kiln
here
getting this:
Cannot convert method group 'FindObjectOfType' to non-delegate type 'Grid'. Did you intend to invoke the method?```
yes that was it ๐
now to try and fix the actual bug which is that I have some objects I want to snap to a grid and am using this function but it snaps the object to the same place on the screen
{
Debug.Log("Pointer up");
var currentPos = transform.position;
transform.position = new Vector3(Mathf.Round(currentPos.x/grid.cellSize.x),
Mathf.Round(currentPos.y/grid.cellSize.x),
Mathf.Round(currentPos.z/grid.cellSize.x));
}```
I'll make a vid
well first
you're dividing all x/y/z by cellSize.x
instead of the corresponding component of cellSize for each dimension
finally - you need to multiply again by cellSize after rounding
๐
Can someone help me with this? Posted earlier but still unable to find a solution. I made this ragdoll and it works how I want in the editor, but not using in-game controls. Will post code in a sec
this is what the code looks like now
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("Pointer up");
var currentPos = transform.position;
transform.position = new Vector2(Mathf.Round(currentPos.x /
grid.cellSize.x) * grid.cellSize.x,
Mathf.Round(currentPos.y / grid.cellSize.y) * grid.cellSize.y);
}
private bool md;
// Start is called before the first frame update
void Start()
{
md = false;
}
// Update is called once per frame
void Update()
{
if(md){
Vector2 np = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = np;
}
}
void OnMouseDown(){
md = true;
}
void OnMouseUp(){
md = false;
}
I kind of fixed it by changing to FixedUpdate() but now it doesnt follow the mouse as well
I identified the issue as a continous force of gravity beign steadily applied.... is there any way to get around this?
Ive toyed with disabling gravity while mouse is down, but this doesnt allow hinged appendages to flop around as wanted
why not just disable gravity on the part you're holding?
also you should really not be modifying the transform of the rigidbody
you should be doing rb.MovePosition - and yes in FixedUpdate
modifying the transform directly is why you're getting the crazy jittering
so:
- Move the thing in FixedUpdate
- Disable gravity on the Rigidbody you're grabbing
- Move the Rigidbody via Rigidbody.MovePosition, not via the Transform
Ive done the first two. The appengages gravity are still weighing the object down. I'll try the MovePosition method instead
Thank you!!!! MovePosition() is exactly what I needed
I tried LERP, MoveTowards, but didnt find MovePosition()
Really appreciate it~
Any thoughts on how to clamp it to the mouse? Currently if I move it too fast it'll jiggle through the mouse rather than hard stop when the mouse does
any idea what @snow willow any idea what's causing this...I multiplied again like you said and am using the correct components this time
How would I combine the velocity of lets say: a spaceship and bullet. The spaceship is moving one direction, and firing a bullet to the side. How would I combine the spaceship's velocity with the bullet's velocity to make the bullet fire realistically?
pointDirection = transform.TransformDirection(Vector3.up * speed);
rb.MovePosition(rb.position + playerVelocity + pointDirection * Time.deltaTime);
^for the bullet
Should I be using AddForce() ?
https://imgur.com/a/rbjWCwD
This kinda works except it exaggerates the player's movement
When you spawn the bullet, give it the same velocity as the ship. Then call AddForce to launch it from the ship
@abstract olive You still around mate ?
Thanks! Works perfectly!
Still trying to make a healthbar appear below my "Player" object. The player object spawns nicely, and in the Start() method of Player, I have this:
void Start() { playerRigidBody = GetComponent<Rigidbody2D>(); SimpleHealthBar healthBar = Instantiate(simpleHealthBar, this.transform, false); healthBar.setMaximumHealth(100); healthBar.setHealth(60); healthBar.transform.localScale = new Vector3(0.002f, 0.001f, 0.0f); }
The bar is spawning (I think) where I want.. and it follows its parent .. I just can't see it! If I pause the game and select the clone, I can see the borders.. with nothing inside.
Any ideas?
@bold plover No crossposting. There are countless tutorials and guides online. Check YouTube.
No
Because the mods are not going to Google translate everything people say in other languages. Please use English.
it takes a long time to write on google translate
I do not know English
is spanish worth? or just english?
Unfortunately , English only. Maybe you can find a Spanish community for Unity.
If you're posting code, it needs to use the proper code tags.
After three attempts you'll likely be temporarily muted.
By the bot
Why are you setting the z scale to 0
@snow willow me ?
@snow willow Setting it to a vector2 with no change to the z axis yields no difference
Noticing something here. If I double click my prefab, I can see my healthbar perfectly, and I can work on it. If I drag my prefab into my scene, it's not visible. Same as I am experiencing when spawning the entity. What can be causing that?
This is the prefab when I am designing it
This is when I have dragged it onto my scene to see if it will paint. Sorry for spam.
is it a UI element? is it an image or a 2d sprite?
if it's a UI element, it needs to be a child of a canvas
Yeah, it's an image
then yeah.it's a UI element and needs to be a child of a canvas
@turbid heart So basically expand the prefab to include a root canvas ..?
no. add an object with canvas component into your scene. and drag your prefab into it
you can try adding an UI element in your scene, you'll see it automatically creates a canvas
@turbid heart the healthbar is getting added programmatically though. Do I just add a canvas to my player object which parents it then?
I dont suggest you do that.. you can, but instead, you're instantiating the healthbar, right? you can assign the parent of the healthbar when you instantiate it
There needs to be a main canvas, and other canvas can go under it
@turbid heart yea, I instantiate it and child it to my player object. The player object is a sprite,but doesnโt have a canvas atm. I was thinking to add a canvas to the player then ?
no, you can't add. please just create an empty canvas
i dont think you can add canvas to a 2d sprite
it has to be empty, or a ui element
if you want, you can try attaching a canvas component to your healthbar I guess..
Setting to a Vector2 also sets z scale to 0
Z scale should be 1
Hey folks. I'm building a 2d melee system and I know of three different ways to create the collision detection. I'm curious what your preferences are, or if anyone knows how AAA games use them?
- by using physics2d to raycast or overlapcircle, record collisions then do something
- Attaching a collider component to an object, animate it, and turn the collider on/off during animation
- attaching collider to empty object over top attack animation and using animator to move/shape the collider
My two cents: People likely all use #1. The second and third option seem to be more physically accurate, with option 2 being less work (Assuming sprites and animations are ready for this method)
you should look at this : https://youtu.be/pQS1mvdD9WA?t=1445
Some nifty little stuff you can see with the hitbox cheat engine tool and a little advertisement for the watchdog mod to stop all the cheat engine abusers. https://www.nexusmods.com/darksouls3/mods/352
#DS3Tube #DarkSouls3 #DS3
I think its usually a combination of 1 and 2, but I could be wrong.
@desert crescent sphere(circle)- and raycasts for ranged and fast moving things (delta-position much bigger than collider-"radius"), colliders parented or following joints with lots of toggle on/off for melee, spells, aoe, ... certainly no deformation of colliders when avoidable. You want to keep iteration of your game feel as simple/quick/fun as possible.
You guys are amazing. Thank you!
For some reason this code seems to be running multiple times when i collide with it how can i make sure it consistently only collides once?
If it's running multiple times you probably have multiple Colliders on one of the objects
It will run for each Collider
Yeah I do but I need the other colliders for other functions so how can i have it happen with just one collider
Layers
I'm posting this again cos I still haven't found out why this isn't working
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("Pointer up");
var currentPos = transform.position;
transform.position = new Vector2(Mathf.Round(currentPos.x / grid.cellSize.x) * grid.cellSize.x,
Mathf.Round(currentPos.y / grid.cellSize.y) * grid.cellSize.y);
}
is snapping everything to (0,0)
just guessing: cellSize is a vector3, maybe your cellSize.y should be cellSize.z @fickle kiln
Debug every step of the way and figure out where the calculation is going wrong
@wise nacelle yes I would like to create a 2d projectile I guess, I have found some reference already thank you
Is there a way to have objects push each other away? I'm thinking of something like a SpringJoint2D, but with a repulsive force (maybe this can be done with SJs but I haven't seen how).
Ideally what I'd want is to have a repulsive force, maybe inverse-square of distance -- or just a spring that pushes rather than pulls.
make each object register itself with a RepulsionFieldManager and iterate over all objects in each FixedUpdate() to apply repulsion between all of them.
basically how you would simulate orbital physics with custom gravitiy vectors between all objects
to optimize performance you could first check which objects are in range of each other before calculating n^2 interactions
I am trying to make a RPG (Enter the gungeon) like room generation, does any one got a good video / source for some information on how to do something like that
void Start()
{
Collider2D border = gameObject.GetComponent<BoxCollider2D>();
border.size = new Vector2(32, 20);
}```
in this example, border.size is seen as invalid. size is not recognized anywhere in intellisense, and it does not compile, despite the documentation stating that it exists
Every other property listed on the documentation I can edit, and if it is a 3D collider I can edit the size, but for a 2D collider, this isn't coming up
What could I be missing
um i was talking about the whole thing, like the room generation, and the difrent size consideration in it, somthing like a artical on tthe subject of even better a YT video on it
I was asking my own question, not responding to yours. Sorry if it seemed that way.
Ah, my mistake. It was because border was of type Collider2D and not BoxCollider2D. Oopsie
oh, ok : )
So, roll my own repulsion? Yeah, that'll work. I was hoping for something built-in I guess. ๐
Fortunately I can avoid the n^2 problem by registering items with a repulsive force between them, which isn't likely to be a lot.
for N < 10 you can usually ignore quadratic complexity
not sure about N < 10, but probably N < 50 anyway
and this isn't a super high performance situation
Heyy ๐ questions about tilemaps
I want to change in game the color of a tile and I'm doing it like so:
tilemap.GetTile<Tile>(pos).color = newColor;
Now, for some reason it won't change the color during the game, but I do see that the tiles have changed after I pause lol
- How can I make them change in game?
- I don't want the actual tile to change color - is there other way of doing it?
Something like this ```cs
/// <summary>
/// Add me to a scene with Repulsor objects (make sure i'm a singleton)
/// </summary>
public class RepulsorSystem2D : MonoBehaviour
{
private static List<Repulsor2D> _repulsors = new List<Repulsor2D>();
public static void Register(Repulsor2D repulsor) => _repulsors.Add(repulsor);
public static void UnRegister(Repulsor2D repulsor) => _repulsors.Remove(repulsor);
private void FixedUpdate()
{
foreach (Repulsor2D me in _repulsors)
{
foreach (Repulsor2D other in _repulsors)
{
Vector3 me2other = other.transform.position - me.transform.position;
other.Rigidbody.AddForce(me2other * (me.Strength / me2other.sqrMagnitude));
}
}
}
}
/// <summary>
/// Add me to objects that repel/attract each other
/// </summary>
[RequireComponent(typeof(Rigidbody2D))]
public class Repulsor2D : MonoBehaviour
{
[SerializeField]
private float strength = 1.0f;
private Rigidbody2D _rigidbody;
public Rigidbody2D Rigidbody => _rigidbody;
public float Strength => strength;
private void Awake() => _rigidbody = GetComponent<Rigidbody2D>();
private void OnEnable() => RepulsorSystem2D.Register(this);
private void OnDisable() => RepulsorSystem2D.UnRegister(this);
}```
Thanks @tame turret -- very nice!
That code is untested ๐
I'm sure it's fiiiiiiine
how can i find out in 2d from which direction a object exits the trigger?
like i have 2 objects
i want to find out if the green object exits from bottom
nevermind found a way thanks anyway ๐
Heyy ๐
I have a tilemap and I want to display some characters above a tile when it's being clicked.
For some reason, I have an enormous offset. I also question the workflow I went with (created custom TilemapData struct based on the tilemap, listening to it and adding floating sprites to the Grid using CellToWorld):
public void UpdateDancers(TilemapData data, Tilemap tilemap)
{
foreach (var tile in data.Tiles)
{
var worldPos = tilemap.CellToWorld(tile.cell);
var newDancer = Instantiate(piggy, transform);
newDancer.transform.position = worldPos;
}
}
}
Hi guys, I have some issue with ledge detection. So the Raycasts work and detect a wall normally, works fine etc. (PlayerLedgeDetect script below) But once I've climbed a ledge/been through the climbing animation every time I face right the Raycasts are showing they're hitting something, but there's nothing there to hit.
On top of this, every time the player isn't grounded, despite the fact that the top Raycast has to be false, it triggers the climbing animation when both Raycasts are true.
The CharacterController2D Script reads the values from the PlayerLedgeDetect script and passes them to a value in the Animator Window:
CharacterController2D Script
https://pastebin.com/drwCCp67
PlayerLedgeDetect Script
https://pastebin.com/UaK4gNH8
I hope it makes sense, thanks
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@turbid heart I finally solved my problem ๐ I ended up adding a canvas to my healthbar prefab, and now it seems to be working nicely! Set the canvas to world position. Child it to my player and now it's following him around like a good puppy!
hey nice! glad you figured out the setting to world position bit too
Haven't quite figured it out yet, but it's all in the process of learning .. so definitely worth the experience!
Is there a way I can check if a player has a bool in a boxcollider trigger?
What does it mean to have a bool in a trigger?
helloooo
i'm having this problem with my animator where my character dose flip but he gets smaller.
heres the code i think needs to be changed
Is your initial scale actually 1?
@vital frost you can just multiply localscale.x by -1 to keep the current scale
like localScale *= new Vector3(-1f,1f,1f)
but then u have to only run that if it changed
so might not be worth it
or maybe using SpriteRenderer.flipX = true instead of scaling X by -1
Hi, I'm trying to use the A* Pathfinding Project but I am running into an issue where enemies will temporarily rotate to the opposite direction for a frame, creating a flickering effect. Here's an example of it happening: https://gyazo.com/c2ac8acb9dc40401d8c77d198f1f02ba
Here's the code, which is mostly taken from Brackey's 2D pathfinding video http://pastie.org/p/61EAuqAEJWW7WcqZ88pWlm
I recommend you this playlist instead if you are not a beginner. https://www.youtube.com/playlist?list=PLFt_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW
Thanks! I'm familiar with that video series. I was thinking of working through it, but I was hoping to save some time on this project. Perhaps now is the time to study pathfinding algorithms.
This will sure be worth your time, but just as a note, please try to understand the algorithm and code fully before typing it and be sure to comment it so you can change it to what you need in the future, good luck!
oh and also, you need to understand basic data structure and algorithms before diving into the series.
Thanks for the warning! I should be alright. Appreciate your advice.
I have a character in a 2D game that i want to make bigger, but when i scale him up as soon an i input anything in the game he goes back to the size he was before, is there anything i can do? im new so sorry if this is a dumb question
we'll probably need to see the script you're using to control the character
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour
{
public float movementSpeed;
public Rigidbody2D rb;
public Animator anim;
public float jumpForce = 8f;
public Transform feet;
public LayerMask groundLayers;
float mx;
private void Update()
{
mx = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
Jump();
}
if (Mathf.Abs(mx) > 0.05f)
{
anim.SetBool("isRunning", true);
}
else
{
anim.SetBool("isRunning", false);
}
if (mx > 0f) {
transform.localScale = new Vector3(1f, 1f, 1f);
} else if (mx < 0f) {
transform.localScale = new Vector3(-1f, 1f, 1f);
}
anim.SetBool("isGrounded", IsGrounded());
}
private void FixedUpdate()
{
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
void Jump () {
Vector2 movement = new Vector2(rb.velocity.x, jumpForce);
rb.velocity = movement;
}
public bool IsGrounded()
{
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
if (groundCheck != null)
{
return true;
}
return false;
}
}```
thats all of it
when i jump the character stays the same, seems to be just when moving left/right he goes back to his original size
1 for sure issue and 1 potential issue:
For sure issue:
look at the code:
if (mx > 0f) {
transform.localScale = new Vector3(1f, 1f, 1f);
} else if (mx < 0f) {
transform.localScale = new Vector3(-1f, 1f, 1f);
}
Notice here, you're setting the character's scale back to 1.
Potential issue:
If your animation on this character modifies the scale of the transform, that will overwrite the value you set in code.
ok i'll change the code and see if it works, ty for the help!
no worries ๐
Is it easy to adopt a new set of tiles if I make an isometric tilemap? I.e, if I use some free tile pack first - will it be hard to switch to a different paid pack at a later time ?
No, you can mix all tilt as long as they are standard, same ratio size
And if they re not, it still tweakable
Hi, i'm having a little problem
I have a character with a sword that rotates into mouse aim but when the character moves the sword stops rotating
can you send the sworld script
I'm sending it but I think i'm doing something wrong??
void FixedUpdate()
{
Rigid.MovePosition(Rigid.position + move * SpeedM * Time.deltaTime);
Vector2 lookDir = MouseP - Rigid.position;
float angLook = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
RigidWp.rotation = angLook;
}
That's the character sc the rotation is bound there
How do you send the scripts like that?
y dont know y usually downlowd the script and then send it
Ah okay
Is this relevant?
to what is the script assigned to
the player
you should make the sworld have its own little script that sympli rotates it
Okay i'll try
and then make the sworld a player child
ill just give you a little script thath does just that wait a bit
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + -90f);
from Blackthorndprod
just assign this to the sworld in a FixedUpdate and it should work
just make sure the camera is set to orthographic or it wont work
happy to help
i go into edit in unity and visual studio
i dont see a settings option
heres my function
called here
ping me when answering
@near bay you need to go inside the edit - project settings - input manager and create the jump input
ah
how do i specify up arrow
wait a minute
k
@near bay Just write up
yes
in the positive slot
what is negative?
you can leave it emphy
it's used for movement
ah
postive is going to return 1
and negative -1
here are all the types of imput
ah ok
how do I make coins float up and down in my game
Add to position y for a bit and then subtract from position y for a bit ๐
Animations or animation curves could also be used
do I have to add a rigidbody to the coin
No
Hi, what can I do if snap to grid doesn't work?
I tried restarting my pc and it still won't work
It works on resizing and rotating
But on moving it won't work
Are you in global tool pivot mode mode or local?
It only works in global
Doesn't work
I tried after this video on world
Still won't work
Blue circle needs to say Global
red circle needs to be toggled on
@snow willow
these kind of toggle always confuse me
It's displaying global cuz its the current state, or it show global cuz if you click it will set to global thus meaning the current state is local
It shows the current state
for example the pause play/stop button is the opposite in unity
How do I make an object bounce off of a wall, but without using a physics material?
Like, if I hit a wall, all my x velocity is flipped.
OnCollisionEnter()
Smacks face
u can also use a string body (idk what's called in unity), and adjust the bounciness
Why does if (other.gameObject.name == "Left") Debug.Log(other.gameObject.name);
Always return every collider name it collides with when other is from OnCollisionEnter(Collision2D other)?
I would expect that to only print "Left"
maybe you have another script that's printing other stuff
or another line of code
More or less it's this debug line
Also I'm getting a Possible mistaken empty statement [Assembly-CSharp] csharp(CS0642) [37,44] Warning. idk if its related though.
Why is there a ; at the end of your if statement?
oh-
You should be getting an error message in the console.. not a warning
yeah it's your semicolon causing it
and that's not a compile error - it just makes your if statement be pointless basically
the only thing that is currently conditional behind the if is the empty statement that is terminated by the semicolon ๐
the warning is telling you exactly that
mhm... Works now, but only if I switch everything to triggers, but that's fine for my purpose.
Hi ppl ๐ Iยดm trying to recreate the mario nes world 1-1 for learning, so i want to achieve that when my playerยดs movement move the camera to the right (when enter in the soft zone of cinemachine and move the camera to right), the player canยดt return to the left bound screen. I look for it in internet but I donยดt know the correct way. I think that put a boxcollider2d as cameraยดs child is not efficient no? (sorry for my english)
there's nothing particularly ineffecient about it - I would just suggest that you give the collider object a Kinematic Rigidbody2D as well
as you should do for any collider that you intend to move
oh thanks ๐ i would like to improve in Unity2d because i want to work in it, I learnt the basic in Unitylearn web and read some books but I donยดt know where to find solutions to my
*to some problems when i canยดt find a solution in google, so here is the correct place? I would like to learn more complex concepts
It means the compiler expected to see a } in your code on line 27, column 80 but it did not.
More broadly it means your code is not structured properly and the compiler cannot make heads or tails of it
Turn them on in Tools -> Options:
Also make sure you have configured it properly to work with Unity: https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity#configure-unity-to-use-visual-studio
Vector3 targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition))
I'm not too sure where i need a
}
can you share the whole script using e.g. https://paste.myst.rs ?
Impossible to know just looking at the one line
you most likely just have mismatched braces
though I will say that line has too many closing parentheses
GameObjectsWithTag
you cannot a transform from a plural group of things
get one, or loop over the collection
ah thanks
Hello, does anyone have a mobile 2D jump script? Thx
How you do jumping depends on your existing character controller. You'll probably find better resources if you separate the input method from the functionality
So guys I have:
โข A Player Prefab w/ a 2D Character Controller attached
โข An Empty Game Object child that contains a BoxCollider2D trigger that's responsible for detecting the ground.
Whenever the BoxCollider2D Trigger touches ground, the player begins descending very slowly. Should i be scouring my code for a solution or is that some kinda issue with Unity's Collision detection?
Probably your code
if(isGrounded && !isOnSlope && !isJumping)
{
newVelocity.Set(xInput * walkSpeed, 0);
player.velocity = newVelocity;
}
else if (isGrounded && isOnSlope && !isJumping)
{
newVelocity.Set(walkSpeed * slopeNormalPerp.x * -xInput, walkSpeed * slopeNormalPerp.y * -xInput);
player.velocity = newVelocity;
}
else if (!isGrounded)
{
newVelocity.Set(xInput * walkSpeed, player.velocity.y);
player.velocity = newVelocity;
}
the only instance where ground check activates and assigns a velocity
Is it just me, or is the default tilemapcollider pretty inaccurate when used for an isometric map ?
https://www.youtube.com/watch?v=TcranVQUQ5U at 10:26 the guy types ''update'' and it gets automatically filled for him, however i dont have this myself, any tips? (im using the latest version of visual studio 2019)
Learn how to make a 2D platformer even if you are a complete beginner. In this episode we're gonna focus on installing Unity and making our player move around and jump.
โ Unity Hub: https://unity3d.com/get-unity/download
โ Black Square Sprite: https://www.shareicon.net/data/256x256/2015/11/08/668660_box_512x512.png
Subscribe and turn on the no...
@solar oyster If you don't have intellisense working in VS then you didn't install it properly, make sure it is set in preferences as default one. Full steps are described in the pinned configuration guide in #๐ปโcode-beginner
what is intellisense? sorry im quite new. Thanks for the answer!
What detects and autocompletes Unity scripts (among other things)
do i have to click on browse? i selected ''visual studio community 2019 [16.9.4]'' before. is that correct?
If that's the one you are using, yes
but why doesnt intellisense work properly?
do i have to get an extension for vs for that?
ty
you mean i should click on browse?
i also cant find that ''editor attaching'' checkbox
if it's not there it's irrelevant
okay, but what should i do next? i followed every step correctly
i pretty much already did all of them before this
next open any script from the editor
you mean double click a script in unity to edit? or in vs itself?
From Unity Editor
this is all i get when i type update? is one of them the one that the guy uses in the video?
again sorry for the dumb questions i started yesterday.
You are most likely outside of the class. Unity methods are right there in the list.
You should not be starting with random tutorials. You need to get some basic understanding of the Engine and scripting. This is a good place to start. https://learn.unity.com/course/create-with-code
tysm!
but this is an explanation of how the code works, i need to get intellisense working first. @lean estuary
You have intellisense, you are not typing in the correct place. Should follow the course.
ok thank you for all your help and have a nice day!
im making a 2d platforme game. and i want my player to do wall jump. but in every tutorial i've watched they let playet do one way wall jump that means player can jump from just one wall. do you have any idea about how to stop it? here's my codes
so how can i change color of 2d object in middle of game
but i also want camera to follow my player but in middle of game when u beat lvl1 camera starts following u how??
when you want to change the color you need to type
sprite.color = new Color(red, green, blue, alpha);
sprite is the sprite renderer
@still tendon Don't crosspost. You're already having a discussion in #๐ปโcode-beginner.
whats a camera following script
A script that makes the camera follow the player but if you want the camera to folow the player y would advice cinemachine
๐
I recommend you to watch the Bardent tutorial on the wall jump. here's the link : https://www.youtube.com/watch?v=5ANjGwcr1hs
Discord Server:
https://discord.gg/uHQrf7K
Assets:
https://drive.google.com/drive/folders/1X_BGNUa75INjJRm0G0sEFd6o8E4Z8N8U?usp=sharing
If you wish to support me more:
https://www.patreon.com/Bardent
How do I setup box colliders on the edge of my camera's view? I tried to line them up manually but the size changes as I enter fullscreen.
Hi, I need help with programming directional input for my enemy AI, I have it set up but don't know how to get it to work in code I've been trying about 2 hours.
Hey does anyone know if I can create randomly generated levels from like a text file and then use that as a basis for instantiating objects
if so how would I go about doing that
which part
Are they randomly generated? Or Are they generated from a text file?
that's a lot of steps
randomly generated text files
sorry should of added that
just all of it tbh, i don't know where to start and where to look for info on it
that's two different problems:
- create the level based on the text file
- randomly create a text file
The more normal way to do it would be:
- randomly create the level
- save the level to a file
- load the level from a file
I mean it's not easy but the high level process is simple to understand:
- create and position the objects in the level
- record the type of object, the position, rotation, scale of each object, and any other data about the object in a single object
- serialize that object (this means convert it to text or binary or whatever)
- save the serialized data to a file
then...
- read the file
- deserailize the contents back to the object that represents the type, position, scale, etc.. about the object
- instantiate the object in the scene and set its position and other properties based on the data you deserialized
Just start with this part:
- create and position the objects in the level
Damn that is very helpful of you, thanks man, that's way easier to start with than "text make things in position I want"
Hi there, uh, so I'm a complete and utter noob, I've never coded anything before and am having to do a simple platformer for class
https://www.youtube.com/watch?v=QGDeafTx5ug&ab_channel=Blackthornprod
I followed along this tutorial, but I can't get my ground check to work, along with some other more minor issues...
The code is here: https://pastebin.com/QRdtfxNZ
and here's a screenshot, showing even though the character's collided with the ground object the ground check still won't activate...
guys can someone help me max 1 min about 2d code thx
@still tendon #๐ปโcode-beginner message
Hi everybody! Could anyone please help me? So I'm making a game where the player moves by shooting explosive bullets and the player moves from the explosion. The bullet only explodes if it collides with something, but if I aim in a corner the player gets twice the force of the explosion and I need to fix this.
Here is some footage:
Is it because you instantiate an explosion on impact and this is creating 2 explosions very near each other?
You could change a boolean like canInstantiateExplosion to false at the end of that collision method and wrap everything in a check if(canInstantiateExplosion){}
and also add a timer, when the timer ends, you flip the bool back to true, essentially making a small cooldown
Okay thank you very much my Idea was to count the collisions and if Its 2 then divide the force by 2 but i somehow failed to implement that. Thanks again
If you want to remove the cooldown, you can do a distance check, and prevent it if the player is being affected by an explosion that is within a certain distance of another
No problems, good luck!
Now it works just like I wanted thanks
When making a 2d isometric game - is it wrong that a character's rigidbody2d has a gravity scale?
Yes, it is wrong. Normally, it should have 0 gravity unless you are doing something quirky.
Nice - ty ๐
Second question. Rigidbody2d. Should it always be moved by using force or is movebody acceptable ?
They do different things and you need to just understand how they work and what the consequences of each are and do whatever fits your desired behavior
why am i only able to have my jump function in my update function
{ Jump();
Dash();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
void Jump(){
if(Input.GetButtonDown("Jump")){
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
void Dash(){
if(Input.GetKeyDown(KeyCode.Q)){
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(5f, 0f), ForceMode2D.Impulse);
}
}
}```
Looks like you've made it a local function embedded inside the Update function; isolating it's scope to the Update function.
how do i make it public
You likely want to put it outside of that scope
Scopes are usually defined with the curly braces.
Wait, is it outside if Update already?
Just make it public using the public modifier prior to void @fast siren
Thought it was a local function sure to a lost of indentation.
its indented i checked
I meant relative to discord ๐
Just place public in from of the return type void.
Wait.
Your misplacing a curly brace.
This is what I'm seeing on my tiny mobile screen: ```
{
Update
{
}
Jump
{
if....
{
Dash
{
}
}
}
}

lmaoo
I was wondering how I would go about creating a "world save system" similar to how minecraft has worlds that you can choose from after creating one?
would i just create multiple save files with different IDs?
I'm assuming the world is procedurally generated so using the same seed would always produce the same results (terrain wise). Likely, they save items and clusters discovered by the users along with the seed. What do you mean by id?
Alright so like in JSON you can encapsulate all data being saved into one string basically, what I would do is everytime I saved, I would then save that json using Unity's playerprefs and create another int or string with an id that increments based on the number of saves that there already is. That would act as the "ID" and then on the front end when the player is choosing what world they want to play in, I can assign the playerprefs ID to that button basically
That way the world is unique for each world, and the data is unique as well
Right, should be fine; definitely need some way to differentiate saved worlds.
Yeah thats what I was thinking I just needed someone to bounce ideas off of. Thanks
how can i make my object go trought object
Don't give it a collider, or set the collider to be a trigger.
but then my player will fall trough
hello how make infinity world system i making game be like growtopia?
Lots of code.
do you have any suggestions about enemy combat? im watching tutorials for 3 hours and i cannot make it work.
How can I make a boss jumo for platforms like this?
Guys, Hope you all are fine.
One quick question.
How many active animation controllers can I have in active scene?
Kian, by the looks of things, only 2 components pop-up to minds. 1. Rigidbody 2D 2. Box-Collider 2D
Then simply, write a simple script and drop on to your boss character gameobject to perform the transitions from one platform to other.
The easier way might be without using physics, and use lerp with sinusoidal offset, it's guaranteed to reach the destination
So I'm just trying to do a simple ground check for a player and some how this code always returns true as if it is always colliding with the ground layer.
Is this code wrong?
Here's my variables set up. Everything matches up, I just quite understand how to get boxcast to work
I would expect OverlapBox not boxcast
For a grounded check
Also the RaycastHit - you need to check if the collider on it is not null
if(raycastHit) < not sure what if anything this actually does
You want if (raycastHit.collider != null)
Thanks. It always returns true no matter what though(and i did make sure its not colliding with the player). I'll have to play with it later.
sorry if this question sounds dumb, im quite new to unity, but this script basically is for a simple square (player) who can move left and right and can jump, but it can jump while in the air, how do i make it detect it when its grounded?
You'll want to lookup tutorials about rigid body and ground detection.
There are quite a few ways to approach this and some at a higher cost than others; but more accurate.
hi
i'm trying to move a gameobject from one place to another in 1 second
but using transform.translate teleports it pretty much
this is my enemycombat script. but they attack always i want him to attack after 3 seconds where am i doing wrong
after first attack attackready set to false but enemy keeps attacking
any way that i can make an object teleport a fixed distance towards the position of the mouse when pressing a button? not setting the velocity but actually moving it the same fixed distance every time
would i use a tangent of the distance i want to to calculate the x and y values to move the object?
nvm :)
no. && is how to write "and' for C# too
Look into Lerp
your CheckInRange is assigning instead of checking equality
please set up your visual studio so it can catch mistakes like that
https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity#configure-unity-to-use-visual-studio
do you have any errors in the console? @green anchor
if (grounded == true)
jumpsLeft = jumpsLeftValue;
i have this code im trying to make a basic character controller
and everything is working except for the jumpsleft value
for such a large chunk of code, you should use a paste site
my bad
ill change it real quick
how do i make it so that jumpsleft isn't made 0 when the player is in the air
because when the player jumps (jumpsLeftValue is 2), jumpsleft turns into 1 for a couple of frames but then is quickly set to 0 without player input
wait
i think the problem is with the input itself
really? have you? because it should have underlined it with a red line
if (Input.GetKey(KeyCode.Space) && jumpsLeft > 0)
Jump();
im not using the right input type am i
can't tell without context on where you're putting it. Where's your full code? Why'd you just remove it?
that's why I said use a paste site
i know that
anyway, I think you mean to use GetKeyDown. You're only wanting to detect the Space key being pressed once, right?
GetKey would return true everytime the key is pressed, held down, and released. Which is why it might fire multiple times in a single keystroke
i tried that but that totally screwed up the movement
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.
well, try setting it up again. it's clearly not set up properly. either way, that's one error. your code probably hasnt compiled because of that error
jumpsleft wouldn't change at all and half of the time the input wasn't registered properly
Input needs to be in Update, not FixedUpdate. FixedUpdate is purely for physics and might fire multiple times per frame
and I still believe you mean to use GetKeyDown
do i just change fixedupdate to update in that case
I think that goes for your moveInput too
no its meant to use getaxisraw
I'm not sure, but your GetKey needs to be in Update for sure
I suggest you read up on the difference yourself ๐ mistakes like this are how you learn
thank you
so i am making a dash function for a 2d platformer, when i release the mouse button, it will calculate the normalized vector pointing from the origin of the player to where the mouse is on the screen, and then using a delta timer, it will set the velocity of the player to the angle vector * dash speed for the time of the dash, which i have set to 0.075 seconds. i am unsure of why, but i am getting a problem where the distance the player covers whenever they release the mouse button is very inconsistent, sometimes going the intended distance, and occasionally stopping early, does anybody know how to fix something like this?
or at least what could be causing the problem with consistency?
can you please show your code?
yeah just a second pls
was fixing it up a little, still sloppy as heck but i hope it's readable
the only thing that has influence over the player velocity other than this is this line of code, which is at the beginning of my update function
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
please use a paste site. see pinned messages in #๐ปโcode-beginner
so the problem is the distance travelled by the dash is inconsistent?
yes, when i release the mouse button, it will go one of two distances
it may be more but i can only tell that it varies between 2
i tested this mainly through setting my mouse to one spot, moving against a wall, and dashing towards the cursor a lot, and it's inconsistent even when the player start position and the mouse position are the same
okay.. I'm not sure yet, but why do you set the body.velocity like this in Update?
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
Won't that mess with the velocity you're trying to set in here?
if (dashing)
{
dashTime -= Time.deltaTime;
// sets body velocity to the angle of the mouse
body.velocity = angle * dashSpd;
// stops the dash if the timer gets too low
if (dashTime <= 0)
{
dashing = false;
body.velocity = Vector2.zero;
}
}
that was the only thing that is on my radar right now
im unsure of how to handle this though ๐ค
should i hand control back to the player only when the dash is fully done?
because I wouldve suspected that maybe your direction vector wasnt normalized, but I can see you did that for angle, and your dashSpd never changes. and your startDashTime never changes too
I'm not entirely sure how your game works ๐
but maybe for this
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
let it only run if dashing is false?
something like
if (dashing == false){
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
}```
probably?
yep
er yeah game is just a simple 2d sidescroller as of right now
I see. I'm just trying to see if it's just some other code that's changing the velocity of your character
so left and right are the only 2 ways to move with space being the only vertical movement
but yeah ill change that rq and see what happens
so unfortunately that was not the problem
damn, i thought maybe it was because of the z axis on the angle, but you got that covered too ๐คฆ I'm stumped, sorry
damn that sucks
I'll look at it somemore. i'll let you know if i think of anything
hopefully i can figure it out :/ i even looked to see if it was a collider issue and it doesnt even seem to be that cuz it happens midair too aaaaaaaa
aight thanks friendo, means a lot
you're sure no other script out there messes with the player's movement?
also, humor me and try putting the dashing = true at the end of the if statement it's in. So, after the angle is Normalized. @meager moat
oh, and do set the dashTime to 0 when you set dashing to false eh, nvm. shouldnt need to..
ill do that anyways just to see if anything happens
no luck :(
can you try debug.logging these things in your if(dashing) statement
angle, dashSpd
see if there's any inconsistencies, like the angle suddenly not being normalized or something
yes
all is well, none of the values look out of line
dash speed doesnt change and the angle vector does not change since im keeping my cursor in place
uh, try recreating the inconsistency then see the debug.log..?
it happened when i was looking at those values
and nothing looked out of the ordinary for those 2
give me a moment to test out your code on my own XD I'm really curious so I'm going above and beyond haha
aighty i can get you an idea of the scene im working in
yeah, can you show me how you set up your speed and startdashtime?
I'll comment out all the jump code since I think they're not relevant
there are all the values that i think i changed or have as variables
dont worry about the pointer field since it's for a different time for me
other than those variables, its just 3 squares designed to keep the player in
can you try moving this line
body.velocity = angle * dashSpd;
to this if statementInput.GetMouseButtonUp(0)
sorry, I really have no clue now @meager moat
unfortunate
How would I be able to parent a rigidbody to another rigidbody on collision? When I use SetParent, the parented rb seems to obstruct movement on the parent rb
rigidbodies don't really respect the transform hierarchy - child RBs will still move independently of parents. There's two main options:
- Make the child RB Kinematic - then it will respect the hierarchy and not interact with the parent
- Use a Physics Joint (e.g. FixedJoint) to "weld" the two together (without parenting). This will act is if you had physically fastened the two objects together.
Gotcha. I'm trying the FixedJoint approach, but for some reason once I detach the child object and try to add a force to it, it just stays still. Does FixedJoint mess with the object's physics?
void Launch(Vector2 direction)
{
joint.connectedBody = null;
rb.isKinematic = false;
equipped = false;
rb.AddForce(direction.normalized * shootForce, ForceMode2D.Impulse);
}
yes of course - that's the point of the joint. But if you connect the joint to null (joint.connectedBody = null) then it will fix the body to an empty position in space
you have to destroy the joint to stop it from influencing the body
Oh I see
unfortunately there is no enable/disable for joints
So if I wanted to be able to attach and reattach the object, I'm going to have to keep creating and destroying the component? Wouldn't that lead to performance overhead?
everything you do has performance overhead
for a single joint it will be fine
I'm trying to use Vector2.Dot to find how closely something is pointing towards another gameobject.
Vector3 direction = Player.transform.position - transform.position;
Debug.Log(Vector2.Dot(transform.up,direction));```
This can output numbers up to nine, but the docs say it ranges from -1 to 1
normalize direction first
it only stays in -1 to 1 for unit vectors
How do I normalize it?
direction.Normalize();
or Vector3 direction = (Player.transform.position - transform.position).normalized;
Okay thanks. Can you tell me what normalizing it does exactly?
it makes a vector that is pointing in the same direction but has a length of 1
instead of whatever its length was
basically:
myVector = myVector / myVector.magnitude;
Right...
๐
Hi
Can someone help me to make my first 2D Game in Unity with C#?
If you have a question just state it
idk i never did anything in unity. I need a full tutorial to do anything like movement or placing yk
There are tutorials for that on youtube. Full fledged ones.
Try BlackThornProd, Brackeys, Sebastian Lague...
okay i will
So i have a problem here
my code is complaining about something i havent been able to fix
whats the issue
Youโre accessing something thatโs null on line 11 in your Grounded script
and that means? Im kinda new to unity and stuff
Also, you dont need gameObject.transform. Just transform will do
okay
That means youโre trying to use something that hasnโt been assigned to
is this what you mean?
Double click the error message and itโll take you to the line with the problem
thats the line
Yes. Thatโs better
Is the object actually a child of another?
okay but it still does say the error
Then.. does your object have a parent
Then are you assigning an object to Cube in your inspector?
Show us the hierarchy. Are you sure this is the Grounded script?
yes
(other script)
It's either:
- You haven't assigned
Cube - Cube isn't a child of another transform
Easy to check, easy to fix.
What object is the script attached to
They are trying to assign to Cube though
Sorry, yes. On mobile, just skimmed the code.
like what i want is movement script to disable jump when Ground check's box collider is hitting the ground
I mean
oops
Is enable
it
So you cannot spam spacebar and fly
Can you please debug log transform.parent before you assign to Cube in start
Let us know what it prints
and how is that done
unity or Visual studio
It prints whatever you put in it to the console where youโre seeing the error too
Well, i said in start, so obviously visual studio
okay
Just google debug log Unity
ok
can anyone help me?
the first result is Unity documentation with some code, is it that?
Just tell us what the issue is
i am trying to create gravity for my game and everytime i add velocity it marks it as incorrect
Just find out how to use Debug.Log then use it to see what transform.parent is
Well what does the error say?
Follow the instructions in the error message?
Infront or after?
?
Yeah, now try that and let me know what it prints. I trust you understood what i meant on where to put it
okay
Check the console and see what the error is
where can i see the debug log?
Hover over the red line and let us know what it says
In unity's console
ok
Im new but Im pretty sure you dont use Debug.Log for a game object
Mostly use it for values
Okay good. Thatโs how you check the value of things. You can see itโs not null. Now can you try changing your Start to Awake?
You can use it for objects. Theyโre also values. You can use it for whatever
Ah so you can use it to check if the gameobject is there
what then
Do you seriously need me to tell you to test everytime? Shall i go over there and press play for you?
hey sorry
Also make sure itโs spelled exactly as Awake
Iโm more interested in if thereโs still the error
Well thank goodness i assumed you didnโt type it in correctly the first time then
Again, are you still getting the null ref error?
let me see
Did you save your script and press play again?
I'll now try the old Cube = transform.parent.gameObject;
to see if there are any errors
Why are you telling me this? And what do you mean old. Did you remove it?
no?
wait
Im not getting any null ref errors
Only the debug logs thing it says
My script is now (and has been)
Oh my goodness ๐คฆ
yes i am dumb
Your words not mine
I said just put transform.parent inside the Debug.Log. Whyโd you put your whole assigning line in it? I think that makes it not assign at all.
Look, just put your old code back, and keep your Start as Awake. Somehow youโre not getting any errors
Okay
Iโm done helping
Sorry to interrupt, I have a question. I have a text component in this game object that keeps getting covered by another game object within the object.
How do I make the "1" in front of the yellow counter? I tried changing the yellow disk's z position but to no avail, and I don't see a setting in the Text Component section that could help(?)
And no, I don't want the image component to be on the same game object as the text component. I'm trying to make a system involving a changeable stack of circular counters with a number displaying how many there are.
Are these UI elements?
Yes
Im new but maybe you can use order in layers or layers
I donโt think UI is affected by z pos. itโs affected by hierarchy
i'll just go watch another tutorial and delete this all
So since your image is your textโs child, itโs going to be in front of it
Oh i just realised it's Text so theres no order in layers lol
Just swap it so that the text is the child of the image
Thank you, that worked. I'm surprised the hierarchy overlaps stuff like that
Destroyer 1(Clone) needs to use GameObject.Find("Player");
but it can't find it.
Should work fine (though I would recommend at least FindWithTag instead of Find)
Hmm... FindWithTag isn't working either
UnassignedReferenceException: The variable Player of Turrent has not been assigned.
You probably need to assign the Player variable of the Turrent script in the inspector.
They work assuming:
- The player is named or tagged the same thing you're searching
- The player exists when you call the function
- The player object is active when you call the function
show code maybe?
And yes, the player is in the scene when the game starts, tagged and is active.
Only stopped working when the destroyer was instantiated from a gameobject that used DontDestroyOnLoad
Hold on...
Somethin funky happened... I'm taking a break so somebody else can use this channel
guys I'm working on a 2d platformer
and my pc crashed today
and unity won't open the project at all
it works normally with other projects
except that one
pls
im working on 2d platformer game and i have enemy prefab that i want to spawn enemies at random spots in map. i also want them to patrol. i was watching the patrol video and had some issues. i have to make the waypoints as a child object to enemy. if i do that it doesnt work well. any ideas?
What do you mean by "If I do that"? Did you mean, by setting parent/child gameobjects? Also, I don't see any line of code which instantiates GO or sets it's parent.
