- Home /
Diagonal speed too fast with 0.7 multiplier
I worte a dash script and I'm currently trying to add a charged dash attack, EVeryything works fine (up until now). For some reason now my diagonal dashes are too fast, evern though I added a 0.7* (√2) multiplier to both forces.
This is the important part of the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movements : MonoBehaviour {
public float speed = 1;
public float DashSpeed = 10;
public float DashSpeedVert;
public float RigDrag = 1;
public float DashCD;
public float DashCDTime;
public bool ChargedDash;
void Start () {
GetComponent<Rigidbody2D>().drag = RigDrag;
DashSpeedVert = DashSpeed * 0.7F;
}
void Update () {
if(DashCD > 0){
DashCD -= Time.deltaTime;
}
if(DashCD < 0){
DashCD = 0;
}
if(Input.GetKeyUp(KeyCode.LeftShift) && DashCD == 0){
if(Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.W)) {
if (DashCD > DashCDTime) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * DashSpeedVert, ForceMode2D.Impulse);
GetComponent<Rigidbody2D>().AddForce(Vector2.left * DashSpeedVert, ForceMode2D.Impulse);
DashCD = DashCDTime;
ChargedDash = true;
}
else{
GetComponent<Rigidbody2D>().AddForce(Vector2.left * DashSpeedVert, ForceMode2D.Impulse);
GetComponent<Rigidbody2D>().AddForce(Vector2.up * DashSpeedVert, ForceMode2D.Impulse);
DashCD = DashCDTime;
}
}
Answer by DarkToadster · Mar 18, 2018 at 03:55 PM
Also don't call GetComponent that often. As you only need the reference once, why not make a global var containing the object.
public Rigidbody2D rb2d;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
rb2d.AddForce(someValue);
}
Answer by toddisarockstar · Mar 18, 2018 at 03:49 PM
i think there would be a more organized approach to your script. i would organize it something like this and maybe it would be easier to find your problem:
float x;
float y;
float s;
public float speed = 10;
public float AddSpeed = 5;
void Update(){
x = 0;y = 0;
s = speed;
if (Input.GetKeyDown (KeyCode.LeftShift)){s += AddSpeed;}
if(Input.GetKey(KeyCode.A)){x = s;}
if(Input.GetKey(KeyCode.D)){x = -s;}
if(Input.GetKey(KeyCode.W)){y = s;}
if(Input.GetKey(KeyCode.S)){y = -s;}
//if absoute values of your axises add too high, ya know the user is pushing diagnally !!!
if(Mathf.Abs(x)+Mathf.Abs(y)>s){x*=.7f;y*=.7f;}
GetComponent<Rigidbody2D>().AddForce(new Vector2(x,y), ForceMode2D.Impulse);
}
Your answer
Follow this Question
Related Questions
Diagonal Dash 1 Answer
Weird angle returned 1 Answer
negative x value in Vector2 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers