K
K
Krevetka3542020-09-01 18:53:48
Unity
Krevetka354, 2020-09-01 18:53:48

Jump not working in unity game, what's wrong with c# code?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveplayer : MonoBehaviour
{
   Animator anim;
   Rigidbody2D rb;
   public GameObject leftbtn ;
   public GameObject rightbtn;
   public GameObject jumpbtn ;
   float posJumpBtn;
   float posbtnright;
   float posbtnleft;
   float run;
   bool whenlook ;





    void Start()
    {
        posbtnright = rightbtn.transform.position.y;
        posbtnleft = leftbtn.transform.position.y;
        posJumpBtn = jumpbtn.transform.position.y;
  
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();

    }

   
    void Update()
    {    if (posJumpBtn != jumpbtn.transform.position.y){
        rb.AddForce (transform.up * 350f  , ForceMode2D.Impulse);
    }

        if(posbtnleft != leftbtn.transform.position.y){
            run = -600f;
            whenlook = false ;
            Flip();
        }
        else if(posbtnright != rightbtn.transform.position.y){
           run = 600f ;
           whenlook = true;
            Flip();
        }  
        else { run = 0f;
        }
        rb.velocity = new Vector2 (run,rb.velocity.y);

        
    }
   void Flip(){
       if(whenlook == false){
           transform.localRotation = Quaternion.Euler(0,0,0);
       }
   
    if (whenlook == true ){
       transform.localRotation = Quaternion.Euler(0,180,0);
       }
   } 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ReWire_92, 2020-09-01
@ReWire_92

void Start()
{
posbtnright = rightbtn.transform.position.y;
posbtnleft = leftbtn.transform.position.y;
posJumpBtn = jumpbtn.transform.position.y;

<b>rb = GetComponent();
anim = GetComponent();</b>

}

I didn’t really read it, but already from the first lines you can see the jamb, which most likely is the problem. What are you trying to assign to the rb and anim variables? Invalid syntax.
Manual on GetComponent
Instead of the code above, you need to use
rb = GetComponent<RigidBody2D>();
anim = GetComponent<Animator>();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question