- Home /
gameobjects(player) slides automatically
Could anyone tell me why the player moves towards left automatically? I think the code will tell the player to move horizontally only when horizontalInput is given? however, my player just keeps moving left without pressing anything. the following is the code, thx a bunch.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerControl : MonoBehaviour { // Start is called before the first frame update void Start() {
}
public float speed = 100;
public float horizontalInput;
public float forwardInput;
public float xrange = 10;
public GameObject projectileprefab;
public float zrange = 10;
// Update is called once per frame void Update() { //the player can not exceed -xrang if (transform.position.x < -xrange) { transform.position = new Vector3(-xrange, transform.position.y, transform.position.z); }
//the player can not exceed xrang
if (transform.position.x > xrange)
{
transform.position =
new Vector3(xrange, transform.position.y, transform.position.z);
}
//the player can not exceed zrang
if (transform.position.z > zrange) {
transform.position =
new Vector3(transform.position.x, transform.position.y, zrange);
}
//the player can not exceed 0
if (transform.position.z <0)
{
transform.position =
new Vector3(transform.position.x, transform.position.y, 0);
}
//control horizontal walk
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
//control backwalk and moving forward
forwardInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(projectileprefab,
transform.position+new Vector3(0,2,0), projectileprefab.transform.rotation);
}
}
}
Your answer
Follow this Question
Related Questions
How to make camera position relative to a specific target. 1 Answer
Controlling Unity3d From Outside 3 Answers
character controll 6 Answers
Interactively moving a game object in a circle 1 Answer
How to Select a Focus Control? 1 Answer