Problem coding script for paddles in Pong without using any physics.

Hi, I’m having some trouble trying to create Pong from zero and I’d like to recreate the game without using any physics. (No rigidbody or collider components)

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

public class Paddle : MonoBehaviour {

        public KeyCode up, down;
        public float speed;
        private CharacterController movement;

	// Use this for initialization
	void Start () {

        movement = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {

        Vector3 move = new Vector3(0, Input.GetKeyCode, 0);
        movement.Move(move * Time.deltaTime * speed);

    }
}

This is so far my script, I’m having trouble in the following line:

Vector3 move = new Vector3(0, Input.GetKeyCode, 0);

I’d like to use the same script for both paddlers (Writing in the inspector the keys I’d like to use for movement), yet I’m unable to figure out a way to summon GetKeyCode in that line.

Any help please? It’ll be highly appreciated.

First, I don’t see a reason to use CharacterController. Simply change the transform position with transform.Translate instead of movement.Move.

Second, Input.GetKeyCode is not a valid method.

What you could do is the following:

 public class Paddle : MonoBehaviour {
 
         public string axis;
         public float speed;
 
     void Update () {
         Vector3 move = new Vector3(0, Input.GetAxis(axis) * Time.deltaTime * speed, 0);
         transform.Translate(move);
     }
 }

set “axis” to the name of the axis for this player (you need to define the axis in the Input Manager window), and you can set a different one for each paddle.
Note that I also multiplied the axis value by Time.deltaTime (the frame length) and the speed.


If you don’t want to use axis, and instead set keys, then you can use the following:

  public class Paddle : MonoBehaviour {
          public string up, down;
          public float speed;
  
      void Update () {
          KeyCode upKey, downKey;
          upKey = (KeyCode )System.Enum.Parse(typeof(KeyCode ), up);
          downKey= (KeyCode )System.Enum.Parse(typeof(KeyCode ), down);
          float yMove = Input.GetKey(upKey) ? 1 : (Input.GetKey(downKey) ? -1 : 0);
          Vector3 move = new Vector3(0, yMove  * Time.deltaTime * speed, 0);
          transform.Translate(move);
      }
  }

Then you set the “up” and “down” for each paddle, as string. The possible values can be found here.

(Yeah, I’d really like to use the set keys.)

Also, thanks for the reply! However, the Monodevelop Unity uses doesn’t have ‘Enum.TryParse’… “‘Ennum’ doesn’t contain a definition for ‘TryParse’.” Should I use ‘Enum.IsDefined’?