• 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.
    • 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.

Solved - C# Setting initial speed force using Float?

Status
This thread has been solved! Go to solution…

DoomPriestK

Coder
Nov 30, 2019
31
10
8
I need to be able to set an initial burst of speed on an item using a Float, I can probably get this to work without the float input but it's quite important the player is able to set the force using the inspector:

Anyone have any ideas on how to accomplish this without changing to a bool or something?

Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerThrowingNut : MonoBehaviour
{
    public float nutSpeed;
    public GameObject nutHitEffect;
    private int myLayer = 8;

    private Rigidbody2D theRB;
    
    // Start is called before the first frame update
    void Start()
    {
        theRB = GetComponent<Rigidbody2D>();
        gameObject.layer = myLayer;
        Physics2D.IgnoreLayerCollision(myLayer, myLayer, true);

        // GETS WHERE THE CURSOR IS ON THE SCREEN
        Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        // LOOK TOWARDS THE CURSOR
        transform.LookAt(Vector3.zero);

        // THEN ADD INITIAL VELOCITY
        theRB = AddForceAtPosition(nutSpeed);

    }

    // Update is called once per frame
    void Update()
    {




    }

    // WHEN IT COLLIDES WITH SOMETHING....
    void OnTriggerEnter2D(Collider2D other)
    {
        // IF THE OTHER OBJECT IS SET TO THE "Killable" LAYER
        if (other.gameObject.layer == LayerMask.NameToLayer("Killable"))
        {
            // SPAWN A HIT GRAPHIC THEN DESTROY THE PROJECTILE
            Instantiate(nutHitEffect, transform.position, transform.rotation);
            Destroy(gameObject, 1.0f);
        }
    }
}
 

DoomPriestK

Coder
Nov 30, 2019
31
10
8
Can you provide the solution?
Sure, code I used is below, it's works in conjunction with the script I use on my ThrowPoint to always look at the mouse cursor (ill post that code underneath it), and also worth noting im trying to strip out the speed and destroyafter and put those on the projectile itself (thats in the other question I posted) but here it is:

Code (In player controller script):

PlayerController Script:
        // IF THROW COOLDOWN IS FINISHED

        if (Time.time > throwNextTime)

        {

            // THROW PROJECTILE

            if (Input.GetKey(throwItem))

            {

                // START COOLDOWN

                throwNextTime = Time.time + throwCooldown;


                // START COOLDOWN ANIMATION BELOW THIS           


                // SPAWNS THE PREFAB PROJECTILE ASSIGNED IN THE Projectile SECTION

                // OF THE INSPECTOR

                GameObject projectileClone = (GameObject)Instantiate(projectile, ThrowPoint.position, Quaternion.identity);

                anim.SetTrigger("Throw");

                Rigidbody2D theProjectileRB = projectileClone.GetComponent<Rigidbody2D>();

                Vector3 vel = new Vector3(1, 0, 0);

                float angle = ThrowPoint.GetComponent<LookAtCursor>().GetAngle();

                vel = Quaternion.Euler(0, 0, angle) * vel;

                vel *= projectileSpeed;

                projectileClone.layer = projectileLayer;


                // MAKE SURE PROJECTILE WONT HIT OTHER PROJECTILES

                Physics2D.IgnoreLayerCollision(projectileLayer, projectileLayer, true);


                // ADD INITIAL VELOCITY

                theProjectileRB.velocity = vel;


                // DESTROY AFTER TIME SET IN INSPECTOR

                Destroy(projectileClone, destroyAfter);


            }

        }

"Look At Cursor" Code Below (attached to the spawn point of my projectiles)

LookAtCursor:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtCursor : MonoBehaviour
{
    private float angle;
    private Camera theCam;

    public float GetAngle() { return angle; }

    // Start is called before the first frame update
    void Start()
    {
        theCam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        //WHERE IS THE MOUSE?
        Vector3 mouse = Input.mousePosition;

        // CALCULATE THE ANGLE OF THE MOUSE
        Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);

        // CALCULATE DIFFERENCE BETWEEN MOUSE AND PLAYER
        Vector2 offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);

        // CONVERT TO DEGREES
        angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        
        // ROTATE!
        transform.rotation = Quaternion.Euler(0f, 0f, angle);


    }
}
Hope this helps someone!
 
  • Like
Reactions: Master Yoda

Master Yoda

Administrator
Administrator
Verified
Jan 2, 2018
1,722
432
95
Canada
codeforum.org
Sure, code I used is below, it's works in conjunction with the script I use on my ThrowPoint to always look at the mouse cursor (ill post that code underneath it), and also worth noting im trying to strip out the speed and destroyafter and put those on the projectile itself (thats in the other question I posted) but here it is:

Code (In player controller script):

PlayerController Script:
        // IF THROW COOLDOWN IS FINISHED

        if (Time.time > throwNextTime)

        {

            // THROW PROJECTILE

            if (Input.GetKey(throwItem))

            {

                // START COOLDOWN

                throwNextTime = Time.time + throwCooldown;


                // START COOLDOWN ANIMATION BELOW THIS          


                // SPAWNS THE PREFAB PROJECTILE ASSIGNED IN THE Projectile SECTION

                // OF THE INSPECTOR

                GameObject projectileClone = (GameObject)Instantiate(projectile, ThrowPoint.position, Quaternion.identity);

                anim.SetTrigger("Throw");

                Rigidbody2D theProjectileRB = projectileClone.GetComponent<Rigidbody2D>();

                Vector3 vel = new Vector3(1, 0, 0);

                float angle = ThrowPoint.GetComponent<LookAtCursor>().GetAngle();

                vel = Quaternion.Euler(0, 0, angle) * vel;

                vel *= projectileSpeed;

                projectileClone.layer = projectileLayer;


                // MAKE SURE PROJECTILE WONT HIT OTHER PROJECTILES

                Physics2D.IgnoreLayerCollision(projectileLayer, projectileLayer, true);


                // ADD INITIAL VELOCITY

                theProjectileRB.velocity = vel;


                // DESTROY AFTER TIME SET IN INSPECTOR

                Destroy(projectileClone, destroyAfter);


            }

        }

"Look At Cursor" Code Below (attached to the spawn point of my projectiles)

LookAtCursor:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtCursor : MonoBehaviour
{
    private float angle;
    private Camera theCam;

    public float GetAngle() { return angle; }

    // Start is called before the first frame update
    void Start()
    {
        theCam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        //WHERE IS THE MOUSE?
        Vector3 mouse = Input.mousePosition;

        // CALCULATE THE ANGLE OF THE MOUSE
        Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);

        // CALCULATE DIFFERENCE BETWEEN MOUSE AND PLAYER
        Vector2 offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);

        // CONVERT TO DEGREES
        angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
       
        // ROTATE!
        transform.rotation = Quaternion.Euler(0f, 0f, angle);


    }
}
Hope this helps someone!
Thank you :)
 
Status
This thread has been solved! Go to solution…