Normalized doesnt work

Hi I’m trying to add speed to projectile when target is too close projectile speed decrease drastically. When it is far there is no problem but when it’s too close this happening

public class Mp5 : MonoBehaviour
{
    private GameObject[] target;
    public GameObject projectile;
    AudioSource source;
    public AudioClip mp5sound;

    float range = 2f;

    Vector3 direction;

    float time = 1f;
    float getTime;
    Vector2 next;
    float nextv;
    Vector2 closest;
  
    float closestv=Mathf.Infinity;
    GameObject closeste;
    bool timeb;
    void Start()
    {
        source = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
       
        timer();
        if(timeb)
        {
          
                timeb = false;
                getTime = time;

         

            turn();
            shoot();
        }
    }


    void turn()
    {
      
        float x = Input.GetAxis("Horizontal");
        if (x < 0) transform.localScale = new Vector3(-1, 1, 1);
        else if (x > 0) transform.localScale = new Vector3(1, 1, 1);
         direction = closestEnemy().transform.position - transform.position;
        Mathf.Atan2(direction.y, direction.x);
        direction.Normalize();
        Quaternion rotation = Quaternion.LookRotation(direction);
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle);


    }

    void shoot()
    {
        if (direction.magnitude <= range)
        {

            source.PlayOneShot(mp5sound);

          
            GameObject bullet = Instantiate(projectile, transform.position, transform.rotation);

            bullet.GetComponent<Rigidbody2D>().velocity=(direction * 3000f * Time.deltaTime);
        }
     
    }

    void timer()
    {
      
        if (!timeb)
        {
            getTime -= Time.deltaTime;

        }
        if (getTime <= 0) timeb = true;

    }

    GameObject closestEnemy()
    {
        GameObject cloesest=null;
        float cloesestdist = Mathf.Infinity;
        target = GameObject.FindGameObjectsWithTag("Enemy");
        foreach(GameObject t in target)
        {
           
          
            float nextv = Vector2.Distance(t.transform.position, transform.position);
              nextv = Mathf.Abs(nextv);
          
            if (nextv < cloesestdist)
            {

                cloesest = t;
                cloesestdist = nextv;
              


            }
              
        }
        return cloesest;
    }

  


  

}

Normalized used by thousands of devs works just fine. Perhaps it’s your code?

1 Like

Do you have any idea I Couldn’t figure it out . Code is on the top

Your rough description of the problem which isn’t clear and the code snippet which shows playing a sound, doing a normalize, creating an object then adding a force doesn’t seem to mean anything I can figure.

You need to put some effort into describing the problem and showing some useful code. We don’t even know what “direction” is. What debugging have you done?

Just not enough info.

I added direction vector

Do you know what AddForce does? The fact that you’re time-integrating it shows you don’t. AddForce adds to an accumulated forced which is processed during the simulation step. You don’t time-integrate it. This is probably why you’re scaling by 30,000!

Just set the velocity of the projectile to the “direction * speed-of-projectile”. Done.

bullet.GetComponent<Rigidbody2D>().velocity = direction * speedOfProjectile;

I added all the codes is it okey now

ı did still doesnt work

bullet.GetComponent<Rigidbody2D>().velocity=(direction * 3000f * Time.deltaTime);

You don’t time-integrate velocity. I would suggest going through some 2D physics tutorials.

I deleted the time.deltatime still doesnt work

Then you’re on your own. I told you how to do it above but if you don’t read what I put then I cannot help you further.

I changed the code like you said .I understand you dont multiply velocity with time thing but still doesnt work bullet.GetComponent<Rigidbody2D>().velocity=(direction * 1f );

And this means what? The code above will move it in the direction 1m/s. Multiplying by 1 does nothing, it’s already normalized so is already length 1.

Don’t say “doesn’t work” and expect someone else to both know what you mean and somehow be able to debug your project. You must provide information.

it function as speedofprojectile

İt functions as speedofprojectile here ı changed it to 5f bullet.GetComponent<Rigidbody2D>().velocity=(direction * 5f );

I know what it means, I told you how to do it remember?

Maybe you didn’t read when I said…

What does this mean?

İs there any way to put video ı can show .When target is too close to character projectile slows down for example if its distance is 5 10 15 no problem but almost inside of the character projectile slows down

This kind of problem needs you to debug it and not just try to get it working by randomly changing stuff.

For instance, set the velocity to always be a fixed direction/speed. If the projectile changes direction/speed then it’s because it’s colliding with stuff or some other script is doing it. This is debugging.

I cannot tell you what the problem is.

Start debugging. Stop avoiding it. Nobody is going to stare at static code and guess.

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

1 Like

İs there any function that can add velocity respect to angle. Or can I convert angle to vector2

If you have an angle you can make a Quaternion out of it and multiply a vector by it.

float angle = 123;

Quaternion rotation = Quaternion.Euler( 0, 0, angle);  // rotate around Z

Vector3 newVector = rotation * oldVector;
1 Like