Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

Multiple objects have the same code, but they don't work the same way

$
0
0
So that's pretty much it. I'm just learning C# but I think this code *should* work, yet it does something weird. Here's the code. `public class MouseController : MonoBehaviour { private RaycastHit hit; public bool selected = false; public Vector3 location; public static float speed; public GameObject camera; // Use this for initialization void Start () { location = this.transform.position; } // Update is called once per frame void Update () { speed = Time.deltaTime*10; if(Input.GetMouseButtonDown (0) && Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) { if (hit.collider.gameObject.name == this.name) { Debug.Log (this.name); Debug.Log (hit.collider.gameObject.name); selected = true; } else { selected = false; } } if(selected && Input.GetMouseButtonDown (1) && Physics.Raycast(Camera.main.ScreenPointToRay (Input.mousePosition), out hit)) { location = hit.point; } if(location.x - this.transform.position.x > 0.1f && location.z - this.transform.position.z > 0.1f) { this.transform.Translate(speed, 0f, speed); } else if (this.transform.position.x - location.x > 0.1f && this.transform.position.z - location.z > 0.1f) { this.transform.Translate(-speed, 0f, -speed); } else { if(location.x - this.transform.position.x > 0.1f) { this.transform.Translate(speed, 0f, 0f); } else if (this.transform.position.x - location.x > 0.1f) { this.transform.Translate(-speed, 0f, 0f); } if(location.z - this.transform.position.z > 0.1f) { this.transform.Translate(0f, 0f, speed); } else if (this.transform.position.z - location.z > 0.1f) { this.transform.Translate(0f, 0f, -speed); } } } }` it's applied to two different gameobjects, one of them works perfectly, while the other does some weird spiraling motions to get from point A to point B. Parts of the code are completely unnecessary and are there only because I was experimenting to fix the bugs at hand. If any of the variable names are actual parts of the programming language, that isn't an issue here. in the *actual* code, I have them in Croatian. Also, the object that the code works for moves on it's own on startup, so if anyone knows how to fix that, I'd be grateful if they told me.

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>