My code from the challenge

I used the following (under void Update. and also created two variables public speed, private playerX.):

if (Input.GetKey(KeyCode.A) && (!Input.GetKey(KeyCode.D))) {playerX -= speed;}
else if (Input.GetKey(KeyCode.D) && (!Input.GetKey(KeyCode.A))) {playerX += speed;}

playerX = Mathf.Clamp(playerX, -6.5f, 6.5f);
gameObject.transform.position = new Vector2(playerX, transform.position.y);
print (transform.position);

*** SEE REPLY BELOW FOR DELTATIME FIX AND FULL CODE FROM THIS CHALLENGE ***

Also my fix for using a non integer SPEED less than 1 (my speed is 0.1 using this and works great!) and adjusting for deltaTime/frame rate lag.

*** I used a speed value of 0.1 because I think using a speed of 5 and then multiplying by deltaTime is a bit sloppy. Just my opinion. But seems like you would have to tweak it much more than being able to set a static value as opposed to a ever changing ratio against deltaTime. ***

Also, I’m used to WASD, so I’m using A/D to move and put in a handler for if you pressed down both keys at once in order to “cancel each other out”.

I’ve reduced “repeating code” and I’ve also clamped the movement value as that was already covered in previous lessons.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public float speed;

	private float adjSpeed;
	private float playerX;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

		// Frame rate compensation
		print (Time.deltaTime);
		adjSpeed = speed;
		if (Time.deltaTime > 0){adjSpeed = speed - (speed * Time.deltaTime);}
		print (adjSpeed);

		// Check input and add movement values
		if 		(Input.GetKey(KeyCode.A) && (!Input.GetKey(KeyCode.D))) {playerX -= adjSpeed;}
		else if (Input.GetKey(KeyCode.D) && (!Input.GetKey(KeyCode.A))) {playerX += adjSpeed;}

		// Constrain to playfield
		playerX = Mathf.Clamp(playerX, -6.5f, 6.5f);
		// Move player
		gameObject.transform.position = new Vector2(playerX, transform.position.y);
		// Console debug
		print (transform.position);

	}
}

Privacy & Terms