简体   繁体   中英

Right paddle not moving in pong game for unity

I am trying to allow the player, in a pong game, to control both paddles. However, for some reason only one paddle is controllable while the other simply does nothing. Here is an image of the paddle property bar.

在此处输入图片说明

And here is the code to the right most paddle that should be controlled with arrow keys.

    using UnityEngine;

using System.Collections;

public class PaddleRight : MonoBehaviour {

public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp;
void Start()
{


}

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

    float yPos = gameObject.transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);

    if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow)) {
        playerPosR = new Vector3(gameObject.transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
        print("right padddle trying to move");
    }

    gameObject.transform.position = playerPosR;
}

}

I can't seem to figure out anywhere why it won't move.. Please, any help would be awesome because I have checked everywhere at this point. Thanks!

I recreated the problem in a project and found that the only problem with it might be you forgetting that the yClamp is public and its set to 0 in the inspector. Make sure you set yClamp to whatever it should be instead of 0.

I would suggest moving the yPos assignment as well as setting the position inside the if statement as you arent changing those if the player isnt moving.

You can also change gameObject.transform.position to just plain transform.position

here is the refined code:

public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp; // make sure it's not 0 in the inspector!

// Update is alled once per frame
void Update()
{
    if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow))
    {
        float yPos = transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
        playerPosR = new Vector3(transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
        transform.position = playerPosR;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM