Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C# Raycast always shoots right

DoomPriestK

Active Coder
[CODE lang="csharp" title="Raycast Shot"] RaycastHit2D hitInfo = Physics2D.Raycast(BulletShootPoint.position, BulletShootPoint.right);

if(hitInfo)
{
Debug.Log(hitInfo.transform.name);
}[/CODE]

Hi all, my Raycast always shoots to the right, even when the character is facing left, i've tried different ways of getting the characters current position and replacing BulletShootPoint.right but nothing seems to work...

I have other code alsewhere that stops all the child objects of the player from flipping with him but even if I disable that code the Raycast always shoots right, I tried Raycast.forward, replacing BulletShootPoint.right with theRB.localScale.x but that didn't seem to fix it either, the Raycast stopped shooting altogether :(

[CODE lang="csharp" title="Stop Children Flipping"] // IF THE LEFT DIRECTION IS USED
if (theRB.velocity.x < 0)
{

// TURN SPRITE TO FACE LEFT
transform.localScale = new Vector3(-1, 1, 1);

// STOP THROWPOINT TURNING WITH IT (Otherwise projectiles turn too)
foreach (Transform child in transform)
{
Vector3 childScale = transform.localScale;
childScale.x = -1;
child.localScale = childScale;
}

}




// ELSE IF THE RIGHT DIRECTION IS BEING USED
else if (theRB.velocity.x > 0)
{

// TURN SPRITE TO FACE RIGHT
transform.localScale = new Vector3(1, 1, 1);

// STOP THROWPOINT TURNING WITH IT (Otherwise projectiles turn too)
foreach (Transform child in transform)
{
Vector3 childScale = transform.localScale;
childScale.x = 1;
child.localScale = childScale;
}

}[/CODE]

Can someone help me out with where im going wrong?

Thanks!
 
Hi there!

Luckily I have a project which is a 2D hack and slash game and it uses ray casts for hit detection.
First we need to read the -CURRENT- direction of the player, you can for example make a public property or private field if you don't need it outside the class. In my example I recommend public propety, you can just read the localScale field:

  • Declare rotation read-only property - transform field being the player 2d gameobject's transform
Code:
public Vector3 Rotation => transform.localScale.x == -1 ? Vector3.left : Vector3.right;

  • New hit based on rotation - in Update() or FixedUpdate()
Code:
      hitInfo = Physics2D.RaycastAll(transform.position, Rotation, 1, LayerMask.NameToLayer("player"));

My ray cast is little different because it supports multi target combat. You can still use the rotation in yours I believe.

Result should be something like this, no matter of the rotation :) :

1577621790223.png
 
Last edited:
Hi there!

Luckily I have a project which is a 2D hack and slash game and it uses ray casts for hit detection.
First we need to read the -CURRENT- direction of the player, you can for example make a public property or private field if you don't need it outside the class. In my example I recommend public propety, you can just read the localScale field:

  • Declare rotation read-only property - transform field being the player 2d gameobject's transform
Code:
public Vector3 Rotation => transform.localScale.x == -1 ? Vector3.left : Vector3.right;

  • New hit based on rotation - in Update() or FixedUpdate()
Code:
      hitInfo = Physics2D.RaycastAll(transform.position, Rotation, 1, LayerMask.NameToLayer("player"));

My ray cast is little different because it supports multi target combat. You can still use the rotation in yours I believe.

Result should be something like this, no matter of the rotation :) :

View attachment 298


Thanks for the suggestion!, ill give it a shot, it looks like your method may work for me too as my player is placed on the Player Layer and anything destructable is placed on a Killable Layer, the code I wrote stops projectiles hitting each other and the player and registers hitting anything on the Killable Layer instead

@Weboogle if your referring to this exact question it's been asked a few times by other people, this is the only website i've asked this question on though. Most of them assume your not stopping child objects from flipping with the player so the Raycast usually just works automatically, so I came a bit unstuck lol
 
I haven't used Unity in a while but I do have a little bit of experience with it. But, it was mostly 3D work that I did instead of 2D work so I can't really help you at all on this.

But, one thing is that have you looked at the official Documentation? The Documentation explains what the function does, how to use it and even provides working example Code. If you haven't, you might want to take a look the Docs. I'm just asking because a lot of people in Programming never seem to read the Documentation/Manual and instead use online tutorials that explain things poorly and that's how they get bugs in their Code and don't have a clue on what it does.
 
I haven't used Unity in a while but I do have a little bit of experience with it. But, it was mostly 3D work that I did instead of 2D work so I can't really help you at all on this.

But, one thing is that have you looked at the official Documentation? The Documentation explains what the function does, how to use it and even provides working example Code. If you haven't, you might want to take a look the Docs. I'm just asking because a lot of people in Programming never seem to read the Documentation/Manual and instead use online tutorials that explain things poorly and that's how they get bugs in their Code and don't have a clue on what it does.


Yeah I gave the official docs a look, the code made sense but it just doesnt take into account the rotation of child objects, they dont flip with the player as he turns (except a specific throwpoint I currently use for grenades so he can chuck them behind himself), but once I threw out the Raycast it would always shoot to the right (so if player is facing left, the raycast would hit myself)

Sometimes I realize i'm overthinking a problem and that leads to the solution, I tend to watch tutorials then look at the docs to try and understand anything that wasnt explained clearly, that can lead to errors, but I'm just way too far away from being able to simply start writing code from scratch, I find myself just trying to get things work, then copy+paste+modify the code if I think of something that needs to act similar lol.

I have to give the tutorial method some props though, I dont think I would have EVER tried to start coding if I hadnt stumbled across this tutorial and gave it a shot, and coding / designing games is a dream of mine, I just had 0 coding experience and it's difficult sometimes for me to get my head around how things work. I was also smart enough to research which engine to use before starting.

a quick example is getting the properties of another object, seems to me like you almost create a "copy" of the object in the code and get the properties of that rather than just checking the original object. My logical brain tends to ache when thinking about that...

Although considering i've been using unity AND coding for a grand total of 3 weeks, i'm not actually doing that badly lol, my character controller script started as around 60 odd lines, fairly sure i've just passed 800 odd (not taking into account the gaps between functions I create so it's easier for my brain to follow whats happening in the code LOL)

My character started as a 2 player christmas 2d snowball throwing game, at the end of the tutorial you can walk, jump, and throw a snowball:

To view this content we will need your consent to set third party cookies.
For more detailed information, see our cookies page.

As he currently stands after 3 weeks, my character can:

Walk
Run
Jump
Crouch
Walk while crouching
Throw grenades with a right click (they aim at mouse cursor)
Throw smoke grenades with a hold-right-click (they aim at mouse cursor)
Take out his gun with a left click
Put his gun away with a hold-left-click
Shoot his gun along the x-axis

I dont think i've done badly so far lol, although most of the time has been used getting used to what Unity can do, setting up HDRP and such.

Anyway I dont want this to be an essay, maybe eventually I can make a massive series of advice articles on here for people who want to follow suit :)
 
Hm. Interesting.

DoomPriestK said:
my character controller script started as around 60 odd lines, fairly sure i've just passed 800 odd (not taking into account the gaps between functions I create so it's easier for my brain to follow whats happening in the code LOL)
As a suggestion, instead of having one big Player-Controller Script, I suggest splitting-up each gameplay element of the Player into their Scripts. So, one Script is responsible for Movement(Walking, Running, Jumping and Crouching), one for throwing Grenades and one for the Firearm.

The reason I suggest this is because it's not really good to have big massive Scripts for one thing unless it involves a lot of Functions, Maths and Information being done and calculated in it. It also makes the Scripts a lot harder to follow. If you split-up everything depending on what it does, then you can follow everything a lot easier.

Also, avoid putting in big giant gaps. You're just wasting extremely tiny bytes of memory in the file-size. It also causes you to scroll more, which can be annoying and boring.

DoomPriestK said:
Yeah I gave the official docs a look, the code made sense but it just doesnt take into account the rotation of child objects, they dont flip with the player as he turns (except a specific throwpoint I currently use for grenades so he can chuck them behind himself), but once I threw out the Raycast it would always shoot to the right (so if player is facing left, the raycast would hit myself)
Well back to the Documentation, I'm glad that you've read it.

There will be something in the Docs relating to rotating Child-Objects. Although, if I'm correct, Child-Objects are also supposed to move when the Player moves, but that might only be 3D-Mode. Not sure. Have you created an Empty-Object, named it "Player" and put all of the Sprites under that Empty-Parent Object? Maybe that can solve your problem if you haven't done that.
 
Hm. Interesting.


As a suggestion, instead of having one big Player-Controller Script, I suggest splitting-up each gameplay element of the Player into their Scripts. So, one Script is responsible for Movement(Walking, Running, Jumping and Crouching), one for throwing Grenades and one for the Firearm.

The reason I suggest this is because it's not really good to have big massive Scripts for one thing unless it involves a lot of Functions, Maths and Information being done and calculated in it. It also makes the Scripts a lot harder to follow. If you split-up everything depending on what it does, then you can follow everything a lot easier.

Also, avoid putting in big giant gaps. You're just wasting extremely tiny bytes of memory in the file-size. It also causes you to scroll more, which can be annoying and boring.


Well back to the Documentation, I'm glad that you've read it.

There will be something in the Docs relating to rotating Child-Objects. Although, if I'm correct, Child-Objects are also supposed to move when the Player moves, but that might only be 3D-Mode. Not sure. Have you created an Empty-Object, named it "Player" and put all of the Sprites under that Empty-Parent Object? Maybe that can solve your problem if you haven't done that.


Now thats the kind of advice you wonder about for the briefest of time, yet it's incredibly important:

1 - I had wondered if those gaps in the script actually used memory of some kind, thankfully you just answered it! i'll close all the gaps I have

2 - Your suggestion of splitting up the functions, I tried looking into saving the game not long back, and it seemed every tutorial wanted you to save all the declared variables in the Character Controller script, so I thought keeping everything in a single script would be useful and once the game is ready for at least a demo I can add the saving (otherwise I risk forgetting to add any new variables I make to the save script and people will end up spawning with half their stats missing). But I havent looked very deep into it yet because saving isnt important at this stage of the development, I'm guessing you can set it up to save multiple scripts' variables?

3. my parent object is an idle sprite with a rigidbody, all the child objects are invisible points for shooting or grenade angle etc, so theres absolutely no graphical sprites attached as children, it's all handled through the animator (I think you may be referring to the bone-rigging method of animation)

4. Which would you recommend, the animator-style flipbook type of animation, or bone rigging my character? I do want him to seem smooth when changing his states, and getting the animation right is awkward because the transitions arent always smooth, for example you get a single frame of his jumping animation for a split second as he lands on the ground because the transition just doesnt move as fast as you need them to even if they have no exit time :(
 
DoomPriestK said:
1 - I had wondered if those gaps in the script actually used memory of some kind, thankfully you just answered it! i'll close all the gaps I have
Yes. Every character(Letters, Numbers, Symbols and Whitespace) in a File takes up a certain amount of Bytes. Now, text-files and Scripts are generally small in terms of size. Today's computers can store as up to 5TB and for Supercomputers, a lot of Petabytes(PB). Scripts are generally in KB but the more Code that's in a Script/File, the more storage it takes up on the HDD/SDD. But even then, it will be measly in size to the Disk-Drive.

And again, every character takes up a certain amount of Bytes, including Spaces, Tabs and Whitespace. So, your massive gaps will only take up a few Bytes of storage, but, it wastes that storage-space just to hold massive gaps.

DoomPriestK said:
2 - Your suggestion of splitting up the functions, I tried looking into saving the game not long back, and it seemed every tutorial wanted you to save all the declared variables in the Character Controller script, so I thought keeping everything in a single script would be useful and once the game is ready for at least a demo I can add the saving (otherwise I risk forgetting to add any new variables I make to the save script and people will end up spawning with half their stats missing). But I havent looked very deep into it yet because saving isnt important at this stage of the development, I'm guessing you can set it up to save multiple scripts' variables?
I don't think I have seen a Save-Game tutorial that involves saving all of the Variables inside the Character-Controller. If I'm correct, to do a Save-Game Script, it needs it's own Script.

Now, the Character-Controller's job is always to control the Movement of the Player. But, because of those tutorials, it made you think of putting everything relating to the Player inside that one Script. So, now you have Functions("Methods" in Object-Oriented Programming because C# is an OO Language) that control the Movement of the Player, Methods that control how Grenades are thrown and Methods that control the Gun and Raycasting.

Splitting-up your Methods and Classes across Files not only make everything easier to read and expand, it also stops Scripts which were meant for one thing and were originally small, from becoming big and expand to multiple purposes and uses. It also decreases how much storage-space that one large Script takes up on the HDD/SDD.

DoomPriestK said:
3. my parent object is an idle sprite with a rigidbody, all the child objects are invisible points for shooting or grenade angle etc, so theres absolutely no graphical sprites attached as children, it's all handled through the animator (I think you may be referring to the bone-rigging method of animation)
I'm sorry, but I don't get what you mean by "My parent object is an idle sprite with a rigidbody. All the child objects are invisible points for shooting or grenade angle etc." I just don't get what you mean by that.

DoomPriestK said:
4. Which would you recommend, the animator-style flipbook type of animation, or bone rigging my character? I do want him to seem smooth when changing his states, and getting the animation right is awkward because the transitions arent always smooth, for example you get a single frame of his jumping animation for a split second as he lands on the ground because the transition just doesnt move as fast as you need them to even if they have no exit time
Well again, I really only have experience with 3D-Development, not 2D. So, I can't really help you with this one.

All I can say is don't use Unity's built-in Animator for anything else other than for changing States(So, Walking --> Jumping or Crouching --> Standing).
 
I'm sorry, but I don't get what you mean by "My parent object is an idle sprite with a rigidbody. All the child objects are invisible points for shooting or grenade angle etc." I just don't get what you mean by that.

Sorry misread in your previous reply when you said "Have you created an Empty-Object, named it "Player" and put all of the Sprites under that Empty-Parent Object? Maybe that can solve your problem if you haven't done that. ", I guess it doesnt matter if it's 1 sprite or 5.

Just meant I dont have a "right arm", "left arm", "torso" bunch of sprites, just the single one of him stood still lol.
 
DoomPriestK said:
Sorry misread in your previous reply when you said "Have you created an Empty-Object, named it "Player" and put all of the Sprites under that Empty-Parent Object? Maybe that can solve your problem if you haven't done that. ", I guess it doesnt matter if it's 1 sprite or 5.
That's okay.

It does kind of matter on if it's 1 Sprite, 2 Sprites, 3 Sprites etc. As for what I meant, let me explain it.

In Unity, you need to create a new "Empty-Object". This is an Object that will have no Mesh, Sound, Controller etc. Name this new Empty-Object, "Player". After that, move your current Player-Object into this new Player-Object. You're current Player-Object will then become a child under this new Object.

That's generally how it's done anyway and it's what most Developers do as well. As for whether this will solve your problem, I cannot say for sure.

DoomPriestK said:
Just meant I dont have a "right arm", "left arm", "torso" bunch of sprites, just the single one of him stood still lol.
Hm. So, your Sprite is just in a standing-position, with no Animation at all, correct? If so, then how will you know he's crouching, running or holding a Firearm?

If you're going to make this Sprite have Animation, you'll need a Spritesheet. Make one of them if you want to do Animation for this Sprite. There are a lot of tutorials out there on the WWW that can help you with this.
 
That's okay.

It does kind of matter on if it's 1 Sprite, 2 Sprites, 3 Sprites etc. As for what I meant, let me explain it.

In Unity, you need to create a new "Empty-Object". This is an Object that will have no Mesh, Sound, Controller etc. Name this new Empty-Object, "Player". After that, move your current Player-Object into this new Player-Object. You're current Player-Object will then become a child under this new Object.

That's generally how it's done anyway and it's what most Developers do as well. As for whether this will solve your problem, I cannot say for sure.


Hm. So, your Sprite is just in a standing-position, with no Animation at all, correct? If so, then how will you know he's crouching, running or holding a Firearm?

If you're going to make this Sprite have Animation, you'll need a Spritesheet. Make one of them if you want to do Animation for this Sprite. There are a lot of tutorials out there on the WWW that can help you with this.


Ah ok i'll do that empty object now.

He transitions immediately to his Idle animation on play, which is just his idle sprite repeated a load of times (I added him looking about a bit at the end too), from there depending on the action it will transition to the next appropriate animation, my animator is a damn mess, but it's the cleanest version possible i'm thinking, had to make him able to transition from everything to everything else to try and simulate smoothness.

EDIT - I'm currently using the spritesheet from the game Flashback as he does a lot of the same things I want my character to do, but i'll need to get someone to completely redo the spritesheet once I get all his abilities working correctly.
 
Last edited:
Hi there!

Luckily I have a project which is a 2D hack and slash game and it uses ray casts for hit detection.
First we need to read the -CURRENT- direction of the player, you can for example make a public property or private field if you don't need it outside the class. In my example I recommend public propety, you can just read the localScale field:

  • Declare rotation read-only property - transform field being the player 2d gameobject's transform
Code:
public Vector3 Rotation => transform.localScale.x == -1 ? Vector3.left : Vector3.right;

  • New hit based on rotation - in Update() or FixedUpdate()
Code:
      hitInfo = Physics2D.RaycastAll(transform.position, Rotation, 1, LayerMask.NameToLayer("player"));

My ray cast is little different because it supports multi target combat. You can still use the rotation in yours I believe.

Your suggestion worked perfectly, now he RayCasts whichever way he is facing, thanks!

[CODE title="Placed before Start method"] // DECLARES INSPECTOR TOGGLE FOR CHARACTER ROTATION
public Vector3 Rotation => transform.localScale.x == -1 ? Vector3.left : Vector3.right;[/CODE]

[CODE title="To Raycast"] // RAYCAST A SHOT
RaycastHit2D hitInfo = Physics2D.Raycast(BulletShootPoint.position, Rotation);

if(hitInfo)
{
Debug.Log(hitInfo.transform.name);
}[/CODE]
 
Your suggestion worked perfectly, now he RayCasts whichever way he is facing, thanks!

[CODE title="Placed before Start method"] // DECLARES INSPECTOR TOGGLE FOR CHARACTER ROTATION
public Vector3 Rotation => transform.localScale.x == -1 ? Vector3.left : Vector3.right;[/CODE]

[CODE title="To Raycast"] // RAYCAST A SHOT
RaycastHit2D hitInfo = Physics2D.Raycast(BulletShootPoint.position, Rotation);

if(hitInfo)
{
Debug.Log(hitInfo.transform.name);
}[/CODE]

You're welcome. :)
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom