CS185c
Chris Pollett
Apr 22, 2019
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomPosition : MonoBehaviour { // Start is called before the first frame update void Start() { StartCoroutine(RepositionWithDelay()); } IEnumerator RepositionWithDelay() { while (true) { SetRandomPosition(); yield return new WaitForSeconds(5); } } void SetRandomPosition () { float x = Random.Range(-5.0f, 5.0f); float z = Random.Range(-5.0f, 5.0f); Debug.Log("X,Z:" + x.ToString("F2") + ", " + z.ToString("F2")); transform.position = new Vector3(x, 0.0f, z); } }
Which of the following statements is true?
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LookMoveTo : MonoBehaviour { public GameObject ground; // Update is called once per frame void Update() { Transform camera = Camera.main.transform; Ray ray; RaycastHit hit; GameObject hitObject; Debug.DrawRay(camera.position, camera.rotation * Vector3.forward * 100.0f); ray = new Ray(camera.position, camera.rotation * Vector3.forward); if (Physics.Raycast (ray, out hit)) { hitObject = hit.collider.gameObject; if (hitObject == ground) { Debug.Log("Hit (x,y,z) :" + hit.point.ToString("F2")); transform.position = hit.point; } } } }
void Update() { Transform camera = Camera.main.transform; Ray ray; RaycastHit[] hits; GameObject hitObject; Debug.DrawRay(camera.position, camera.rotation * Vector3.forward * 100.0f); ray = new Ray(camera.position, camera.rotation * Vector3.forward); hits = Physics.RaycastAll(ray); for( int i = 0; i < hits.Length; i++) { RaycastHit hit = hits[i]; hitObject = hit.collider.gameObject; if (hitObject == ground) { Debug.Log("Hit (x,y,z) :" + hit.point.ToString("F2")); transform.position = hit.point; } } }
public class KillTarget : MonoBehaviour { public GameObject target; public ParticleSystem hitEffect; public GameObject killEffect; public float timeToSelect = 3.0f; public int score; private float countDown; // Start is called before the first frame update void Start() { score = 0; countDown = timeToSelect; } // Update is called once per frame void Update() { Transform camera = Camera.main.transform; Ray ray = new Ray(camera.position, camera.rotation * Vector3.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit) && (hit.collider.gameObject == target)) { if (countDown > 0.0f) { countDown -= Time.deltaTime; hitEffect.transform.position = hit.point; hitEffect.Play(); } else { Instantiate(killEffect, target.transform.position, target.transform.rotation); score += 1; countDown = timeToSelect; SetRandomPosition(); } } else { countDown = timeToSelect; hitEffect.Stop(); } } void SetRandomPosition() { float x = Random.Range(-5.0f, 5.0f); float z = Random.Range(-5.0f, 5.0f); /* Notice not quite the code as before, now we change target's (Ethan ) position */ target.transform.position = new Vector3(x, 0.0f, z); } }