-1
\$\begingroup\$

I was trying to move object by changing velocity

void FixedUpdate()
    {
        int velocity_x = rb.velocity.x;
        int velocity_y = rb.velocity.y;
        if(Input.GetKey("a")){
            if(velocity_x<0){
                
            }else if(velocity_x>0){

            }
            else{
                velocityChange(-1, 0);
            }
        }else if(Input.GetKey("w")){
            if(velocity_y<0){
                
            }else if(velocity_y>0){

            }
            else{
               velocityChange(0, 1);
            }
        }else if(Input.GetKey("d")){
            if(velocity_x<0){
                
            }else if(velocity_x>0){

            }
            else{
                velocityChange(1, 0);
            }
        }else if(Input.GetKey("s")){
            if(velocity_y<0){
                
            }else if(velocity_y>0){

            }
            else{
               velocityChange(0, -1);
            }
        }
    }

    void OnCollisionEnter2D(Collision2D collision){
        if(collision.collider.tag =="obstacle"){
           Debug.Log("Finish");
        }
    }
    void velocityChange(int velocityX,velocityY){
        rb.velocity = new Vector2(velocityX, velocityY);
    }

But, I am getting error.

Assets/movement.cs(57,48): error CS1001: Identifier expected

57 line :

void velocityChange(int velocityX,velocityY){

48 line :

}

40-49 line :

else if(Input.GetKey("s")){
        if(velocity_y<0){
            
        }else if(velocity_y>0){

        }
        else{
           velocityChange(0, -1);
        }
    }
\$\endgroup\$
2
  • \$\begingroup\$ Those conditions are really redudant, the else block is always checking if it is 0. Since you never use the other two, you can reduce it to: if (Input.GetKey("s") && (velocity_y==0)){ velocityChange(0, -1);} \$\endgroup\$ – Zibelas Feb 17 at 11:35
  • \$\begingroup\$ This doesn't look like a problem with "movement of 2d object" - it looks like "C# syntax errors". That's a general programming topic that's not on-topic here. Please remember to search your error message texts - these are generally covered very thoroughly on our general programming sister site, StackOverflow \$\endgroup\$ – DMGregory Feb 17 at 13:36
0
\$\begingroup\$

In 57 line :

void velocityChange(int velocityX,velocityY){

I didn't specify the type for the velocityY. So, I wrote void velocityChange(int velocityX, velocityY)

Then, I got another error Assets/movement.cs(11,26): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)

I was having the issue cause, rb.velocity.x and rb.velocity.y is float not int. So, i had to convert data types of them also.

float velocity_x = rb.velocity.x;
float velocity_y = rb.velocity.y;
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.