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# Setting initial speed force using Float?

DoomPriestK

Active Coder
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);
        }
    }
}
 
I've been thinking about this and it may be better to set the ThrowPoint direction on the player himself, then just deal with the force on the projectile

It still doesnt solve the problem I dont think, ill investigate shortly.
Let’s us know how it goes!
 
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):

[CODE title="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);


}

}[/CODE]


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

[CODE title="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);


}
}[/CODE]

Hope this helps someone!
 
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):

[CODE title="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);


}

}[/CODE]


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

[CODE title="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);


}
}[/CODE]

Hope this helps someone!
Thank you :)
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom