I’ve created this code to movement a object on X axis, but, I need to limit the movement between the points -5 and 6 (x axis). How I can do this?
using UnityEngine;
using System.Collections;
public class MoveBarra : MonoBehaviour {
public float VelocidadeMov;
void Start () {
VelocidadeMov = .25f;
}
void Update() {
if(Input.GetKey(KeyCode.W))
{
transform.Translate(-VelocidadeMov, 0, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(VelocidadeMov, 0, 0);
}
}
}
hello,
simple replace below line with your line.
transform.Translate(Mathf.Clamp(-VelocidadeMov,-5,6), 0, 0);
At the end add:
If(transform.position.x < -5) transform.position = new Vector3(-5,0,0);
If(transform.position.x > 6) transform.position = new Vector3(6,0,0)
This will limit the value between those value, first line checks if value has gone below lower limit, second line for uppper limit.
abukaff
February 14, 2018, 2:57pm
3
public float speedFactor= 1f;
public float clampDistance = 50f;
private Vector3 startLocation;
/////
void Start () {
startLocation = gameObject.transform.position;
}
///////
void Update () {
Vector3 lastLocation = gameObject.transform.position;
Vector3 movement = new Vector3(Axis.x * speedFactor, Axis.y * speedFactor, Axis.z * speedFactor);
gameObject.transform.Translate(movement);
if(Vector3.Distance(startLocation,gameObject.gameObject.transform.position)>clampDistance)
gameObject.transform.position = lastLocation;
}
where Axis is the input from what ever you want, just swap them as required
I found it, may be it help you @FabioMendes
Hi, I’m new to Unity and I’m trying to clone the Pong game right now but I’m stuck with movement restriction. I found one example that worked, but it worked in JS and I’m trying to learn C# so don’t want to use any JS scripts now. The problem is that...