|
Post by Scriptzz on Oct 18, 2013 9:23:36 GMT
Updated click and move:
var smooth:int; // Determines how quickly object moves towards position
private var targetPosition:Vector3;
var speed = 60;
function Update () {
if(Input.GetKeyDown(KeyCode.Mouse0))
{
smooth=1;
var playerPlane = new Plane(Vector3.up, transform.position);
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hitdist = 0.0;
if (playerPlane.Raycast (ray, hitdist)) {
var targetPoint = ray.GetPoint(hitdist);
targetPosition = ray.GetPoint(hitdist);
var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = targetRotation;
}
}
var dir:Vector3 = targetPosition - transform.position;
var dist:float = dir.magnitude;
var move:float = speed * Time.deltaTime;
if(dist > move){
transform.position += dir.normalized * move;
} else {
transform.position = targetPosition;
}
transform.position += (targetPosition - transform.position).normalized * speed * Time.deltaTime;
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:27:39 GMT
RPG Controller:
using UnityEngine; using System.Collections;
public class RPG_Controller : MonoBehaviour {
public static RPG_Controller instance;
public CharacterController characterController; public float walkSpeed = 10f; public float turnSpeed = 2.5f; public float jumpHeight = 10f; public float gravity = 20f; public float fallingThreshold = -6f; // -6f gets the character beeing almost always grounded
private Vector3 playerDir; private Vector3 playerDirWorld; private Vector3 rotation = Vector3.zero;
void Awake() { instance = this; characterController = GetComponent("CharacterController") as CharacterController;
RPG_Camera.CameraSetup(); }
void Update () { if (Camera.mainCamera == null) return;
if (characterController == null) { Debug.Log("Error: No Character Controller component found! Please add one to the GameObject which has this script attached."); return; }
GetInput();
StartMotor(); }
void GetInput() { //MovementKeys(): float horizontalStrafe = 0f; float vertical = 0f;
if (Input.GetButton("Horizontal Strafe")) horizontalStrafe = Input.GetAxis("Horizontal Strafe") < 0 ? -1f : Input.GetAxis("Horizontal Strafe") > 0 ? 1f : 0f;
if (Input.GetButton("Vertical")) vertical = Input.GetAxis("Vertical") < 0 ? -1f : Input.GetAxis("Vertical") > 0 ? 1f : 0f;
if (Input.GetMouseButton(0) && Input.GetMouseButton(1)) vertical = 1f; playerDir = horizontalStrafe * Vector3.right + vertical * Vector3.forward; if (RPG_Animation.instance != null) RPG_Animation.instance.SetCurrentMoveDir(playerDir);
if (characterController.isGrounded) { playerDirWorld = transform.TransformDirection(playerDir); if (Mathf.Abs(playerDir.x) + Mathf.Abs(playerDir.z) > 1) playerDirWorld.Normalize(); playerDirWorld *= walkSpeed; playerDirWorld.y = fallingThreshold; if (Input.GetButtonDown("Jump")) { playerDirWorld.y = jumpHeight; if (RPG_Animation.instance != null) RPG_Animation.instance.Jump(); // the pattern for calling animations is always the same: just add some lines under line 77 and write an if statement which } // checks for an arbitrary key if it is pressed and, if true, calls "RPG_Animation.instance.YourAnimation()". After that you add } // this method to the other animation clip methods in "RPG_Animation" (do not forget to make it public)
rotation.y = Input.GetAxis("Horizontal") * turnSpeed; }
void StartMotor() { playerDirWorld.y -= gravity * Time.deltaTime; characterController.Move(playerDirWorld * Time.deltaTime);
transform.Rotate(rotation); if (!Input.GetMouseButton(0)) RPG_Camera.instance.RotateWithCharacter(); } }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:29:16 GMT
RPG Camera:
using UnityEngine; using System.Collections;
public class RPG_Camera : MonoBehaviour {
public static RPG_Camera instance;
public Transform cameraPivot; public float distance = 5f; public float distanceMax = 30f; public float mouseSpeed = 8f; public float mouseScroll = 15f; public float mouseSmoothingFactor = 0.08f; public float camDistanceSpeed = 0.7f; public float camBottomDistance = 1f; public float firstPersonThreshold = 0.8f; public float characterFadeThreshold = 1.8f;
private Vector3 desiredPosition; private float desiredDistance; private float lastDistance; private float mouseX = 0f; private float mouseXSmooth = 0f; private float mouseXVel; private float mouseY = 0f; private float mouseYSmooth = 0f; private float mouseYVel; private float mouseYMin = -89.5f; private float mouseYMax = 89.5f; private float distanceVel; private bool camBottom; private bool constraint; private static float halfFieldOfView; private static float planeAspect; private static float halfPlaneHeight; private static float halfPlaneWidth;
void Awake() { instance = this; }
void Start() { distance = Mathf.Clamp(distance, 0.05f, distanceMax); desiredDistance = distance;
halfFieldOfView = (Camera.mainCamera.fieldOfView / 2) * Mathf.Deg2Rad; planeAspect = Camera.mainCamera.aspect; halfPlaneHeight = Camera.mainCamera.nearClipPlane * Mathf.Tan(halfFieldOfView); halfPlaneWidth = halfPlaneHeight * planeAspect;
mouseX = 0f; mouseY = 15f; }
public static void CameraSetup() { GameObject cameraUsed; GameObject cameraPivot; RPG_Camera cameraScript;
if (Camera.mainCamera != null) cameraUsed = Camera.mainCamera.gameObject; else { cameraUsed = new GameObject("Main Camera"); cameraUsed.AddComponent("Camera"); cameraUsed.tag = "MainCamera"; }
if (!cameraUsed.GetComponent("RPG_Camera")) cameraUsed.AddComponent("RPG_Camera"); cameraScript = cameraUsed.GetComponent("RPG_Camera") as RPG_Camera;
cameraPivot = GameObject.Find("cameraPivot") as GameObject; cameraScript.cameraPivot = cameraPivot.transform; } void LateUpdate() { if (cameraPivot == null) { Debug.Log("Error: No cameraPivot found! Please read the manual for further instructions."); return; }
GetInput();
GetDesiredPosition();
PositionUpdate();
CharacterFade(); }
void GetInput() {
if (distance > 0.1) { // distance > 0.05 would be too close, so 0.1 is fine Debug.DrawLine(transform.position, transform.position - Vector3.up * camBottomDistance, Color.green); camBottom = Physics.Linecast(transform.position, transform.position - Vector3.up * camBottomDistance); }
bool constrainMouseY = camBottom && transform.position.y - cameraPivot.transform.position.y <= 0;
if (Input.GetMouseButton(0) || Input.GetMouseButton(1)) { Screen.showCursor = false; // if you want the cursor behavior of the version 1.0, change this line to "Screen.lockCursor = true;"
mouseX += Input.GetAxis("Mouse X") * mouseSpeed;
if (constrainMouseY) { if (Input.GetAxis("Mouse Y") < 0) mouseY -= Input.GetAxis("Mouse Y") * mouseSpeed; } else mouseY -= Input.GetAxis("Mouse Y") * mouseSpeed; } else Screen.showCursor = true; // if you want the cursor behavior of the version 1.0, change this line to "Screen.lockCursor = false;" mouseY = ClampAngle(mouseY, -89.5f, 89.5f); mouseXSmooth = Mathf.SmoothDamp(mouseXSmooth, mouseX, ref mouseXVel, mouseSmoothingFactor); mouseYSmooth = Mathf.SmoothDamp(mouseYSmooth, mouseY, ref mouseYVel, mouseSmoothingFactor);
if (constrainMouseY) mouseYMin = mouseY; else mouseYMin = -89.5f; mouseYSmooth = ClampAngle(mouseYSmooth, mouseYMin, mouseYMax);
if (Input.GetMouseButton(1)) RPG_Controller.instance.transform.rotation = Quaternion.Euler(RPG_Controller.instance.transform.eulerAngles.x, Camera.mainCamera.transform.eulerAngles.y, RPG_Controller.instance.transform.eulerAngles.z);
desiredDistance = desiredDistance - Input.GetAxis("Mouse ScrollWheel") * mouseScroll;
if (desiredDistance > distanceMax) desiredDistance = distanceMax;
if (desiredDistance < 0.05) desiredDistance = 0.05f; }
void GetDesiredPosition() { distance = desiredDistance; desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance);
float closestDistance; constraint = false;
closestDistance = CheckCameraClipPlane(cameraPivot.position, desiredPosition);
if (closestDistance != -1) { distance = closestDistance; desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance);
constraint = true; }
distance -= Camera.mainCamera.nearClipPlane;
if (lastDistance < distance || !constraint) distance = Mathf.SmoothDamp(lastDistance, distance, ref distanceVel, camDistanceSpeed); if (distance < 0.05) distance = 0.05f;
lastDistance = distance;
desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance); // if the camera view was blocked, then this is the new "forced" position }
void PositionUpdate() { transform.position = desiredPosition;
if (distance > 0.05) transform.LookAt(cameraPivot); }
void CharacterFade() { if (RPG_Animation.instance == null) return; if (distance < firstPersonThreshold) RPG_Animation.instance.renderer.enabled = false; else if (distance < characterFadeThreshold) { RPG_Animation.instance.renderer.enabled = true;
float characterAlpha = 1 - (characterFadeThreshold - distance) / (characterFadeThreshold - firstPersonThreshold); if (RPG_Animation.instance.renderer.material.color.a != characterAlpha) RPG_Animation.instance.renderer.material.color = new Color(RPG_Animation.instance.renderer.material.color.r, RPG_Animation.instance.renderer.material.color.g, RPG_Animation.instance.renderer.material.color.b, characterAlpha); } else {
RPG_Animation.instance.renderer.enabled = true;
if (RPG_Animation.instance.renderer.material.color.a != 1) RPG_Animation.instance.renderer.material.color = new Color(RPG_Animation.instance.renderer.material.color.r, RPG_Animation.instance.renderer.material.color.g, RPG_Animation.instance.renderer.material.color.b, 1); } }
Vector3 GetCameraPosition(float xAxis, float yAxis, float distance) { Vector3 offset = new Vector3(0, 0, -distance); Quaternion rotation = Quaternion.Euler(xAxis, yAxis, 0); return cameraPivot.position + rotation * offset; }
float CheckCameraClipPlane(Vector3 from, Vector3 to) { var closestDistance = -1f; RaycastHit hitInfo;
ClipPlaneVertexes clipPlane = GetClipPlaneAt(to);
Debug.DrawLine(clipPlane.UpperLeft, clipPlane.UpperRight); Debug.DrawLine(clipPlane.UpperRight, clipPlane.LowerRight); Debug.DrawLine(clipPlane.LowerRight, clipPlane.LowerLeft); Debug.DrawLine(clipPlane.LowerLeft, clipPlane.UpperLeft); Debug.DrawLine(from, to, Color.red); Debug.DrawLine(from - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperLeft, Color.cyan); Debug.DrawLine(from + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperRight, Color.cyan); Debug.DrawLine(from - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerLeft, Color.cyan); Debug.DrawLine(from + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerRight, Color.cyan);
if (Physics.Linecast(from, to, out hitInfo) && hitInfo.collider.tag != "Player") closestDistance = hitInfo.distance - Camera.mainCamera.nearClipPlane; if (Physics.Linecast(from - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, from);
if (Physics.Linecast(from + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperRight, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, from); if (Physics.Linecast(from - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerLeft, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, from); if (Physics.Linecast(from + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerRight, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, from);
return closestDistance; }
float ClampAngle(float angle, float min, float max) { while (angle < -360 || angle > 360) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; }
return Mathf.Clamp(angle, min, max); }
public struct ClipPlaneVertexes { public Vector3 UpperLeft; public Vector3 UpperRight; public Vector3 LowerLeft; public Vector3 LowerRight; }
public static ClipPlaneVertexes GetClipPlaneAt(Vector3 pos) { var clipPlane = new ClipPlaneVertexes();
if (Camera.mainCamera == null) return clipPlane;
Transform transform = Camera.mainCamera.transform; float offset = Camera.mainCamera.nearClipPlane;
clipPlane.UpperLeft = pos - transform.right * halfPlaneWidth; clipPlane.UpperLeft += transform.up * halfPlaneHeight; clipPlane.UpperLeft += transform.forward * offset;
clipPlane.UpperRight = pos + transform.right * halfPlaneWidth; clipPlane.UpperRight += transform.up * halfPlaneHeight; clipPlane.UpperRight += transform.forward * offset;
clipPlane.LowerLeft = pos - transform.right * halfPlaneWidth; clipPlane.LowerLeft -= transform.up * halfPlaneHeight; clipPlane.LowerLeft += transform.forward * offset;
clipPlane.LowerRight = pos + transform.right * halfPlaneWidth; clipPlane.LowerRight -= transform.up * halfPlaneHeight; clipPlane.LowerRight += transform.forward * offset;
return clipPlane; }
public void RotateWithCharacter() { float rotation = Input.GetAxis("Horizontal") * RPG_Controller.instance.turnSpeed; mouseX += rotation; } }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:31:35 GMT
RPG Animation:
using UnityEngine; using System.Collections;
public class RPG_Animation : MonoBehaviour {
public static RPG_Animation instance;
public enum CharacterMoveDirection { None, Forward, Backward, StrafeLeft, StrafeRight, StrafeForwardLeft, StrafeForwardRight, StrafeBackLeft, StrafeBackRight } public enum CharacterState { Idle, Walk, WalkBack, StrafeLeft, StrafeRight, Jump }
public CharacterMoveDirection currentMoveDir; // this is the current move direction of "PlayerChar" public CharacterState currentState; // this is its current (animation) state
void Awake() { instance = this; }
void Update() { SetCurrentState();
StartAnimation(); }
public void SetCurrentMoveDir(Vector3 playerDir) { // this method is called in "RPG_Controller" in line 60 when it is checking for movement inputs and sets the variable currentMoveDir bool forward = false; bool backward = false; bool left = false; bool right = false;
if (playerDir.z > 0) forward = true; if (playerDir.z < 0) backward = true; if (playerDir.x < 0) left = true; if (playerDir.x > 0) right = true;
if (forward) { if (left) currentMoveDir = CharacterMoveDirection.StrafeForwardLeft; else if (right) currentMoveDir = CharacterMoveDirection.StrafeForwardRight; else currentMoveDir = CharacterMoveDirection.Forward; } else if (backward) { if (left) currentMoveDir = CharacterMoveDirection.StrafeBackLeft; else if (right) currentMoveDir = CharacterMoveDirection.StrafeBackRight; else currentMoveDir = CharacterMoveDirection.Backward; } else if (left) currentMoveDir = CharacterMoveDirection.StrafeLeft; else if (right) currentMoveDir = CharacterMoveDirection.StrafeRight; else currentMoveDir = CharacterMoveDirection.None; }
public void SetCurrentState() { // sets the variable currentState with help of currentMoveDir if (RPG_Controller.instance.characterController.isGrounded) { switch (currentMoveDir) { case CharacterMoveDirection.None: currentState = CharacterState.Idle; break; case CharacterMoveDirection.Forward: currentState = CharacterState.Walk; break; case CharacterMoveDirection.StrafeForwardLeft: currentState = CharacterState.Walk; break; case CharacterMoveDirection.StrafeForwardRight: currentState = CharacterState.Walk; break; case CharacterMoveDirection.Backward: currentState = CharacterState.WalkBack; break; case CharacterMoveDirection.StrafeBackLeft: currentState = CharacterState.WalkBack; break; case CharacterMoveDirection.StrafeBackRight: currentState = CharacterState.WalkBack; break; case CharacterMoveDirection.StrafeLeft: currentState = CharacterState.StrafeLeft; break; case CharacterMoveDirection.StrafeRight: currentState = CharacterState.StrafeRight; break; } } }
public void StartAnimation() { // reads the variable currentState and calls the corresponding animation method switch (currentState) { case CharacterState.Idle: Idle(); break; case CharacterState.Walk: if (currentMoveDir == CharacterMoveDirection.StrafeForwardLeft) StrafeForwardLeft(); else if (currentMoveDir == CharacterMoveDirection.StrafeForwardRight) StrafeForwardRight(); else Walk(); break; case CharacterState.WalkBack: if (currentMoveDir == CharacterMoveDirection.StrafeBackLeft) StrafeBackLeft(); else if (currentMoveDir == CharacterMoveDirection.StrafeBackRight) StrafeBackRight(); else WalkBack(); break; case CharacterState.StrafeLeft: StrafeLeft(); break; case CharacterState.StrafeRight: StrafeRight(); break; } }
// every animation clip has its own method #region Animation Methods void Idle() { animation.CrossFade("idle"); }
void Walk() { animation.CrossFade("walk"); }
void StrafeForwardLeft() { animation.CrossFade("strafeforwardleft"); }
void StrafeForwardRight() { animation.CrossFade("strafeforwardright"); }
void WalkBack() { animation.CrossFade("walkback"); }
void StrafeBackLeft() { animation.CrossFade("strafebackleft"); }
void StrafeBackRight() { animation.CrossFade("strafebackright"); } void StrafeLeft() { animation.CrossFade("strafeleft"); }
void StrafeRight() { animation.CrossFade("straferight"); }
public void Jump() { // this method is an exception because it is called by "RPG_Controller" (line 73) if the jump button was hit. Therefore it has the access level "public". currentState = CharacterState.Jump; if (animation.IsPlaying("jump")) animation.Stop("jump"); animation.CrossFade("jump"); } #endregion }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:41:35 GMT
AI Controller:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class AIController : MonoBehaviour {
public Transform target; public float targetPointHeight = 1.0f; public Transform spawnPoint; public GameObject projectile; private Transform myTargetPoint; private Transform otherTargetPoint; public float movingSpeed = 5; public float rotationSpeed = 0.2f; public float fieldOfView = 180; public float viewDistance = 30; public float attakingDistance = 20; public float minimalDistance = 5;
[HideInInspector] public string idleAnimation = ""; [HideInInspector] public string walkAnimation = ""; [HideInInspector] public string fightAnimation = ""; [HideInInspector] public string hitAnimation = ""; [HideInInspector] public string dieAnimation = "";
public bool crossFadeAnimations = false; public float shootingPause = 2.0f; public float deathDelayTime = 4; //public List<CollisionDamage> CollisionDamages; public float projectileForce = 1000; //public float projectileLifeTime = 2; public float fightEffectsDelay = 0.4f; public bool calculationDamage = true; public int minDamage = 10; public int maxDamage = 15; public int hitChance = 90; public float health = 100; public bool playSound = true; public SoundObject fightSound = new SoundObject(); public SoundObject hitSound = new SoundObject(); public SoundObject dieSound = new SoundObject(); public bool idleStart = false; public float waitingMaxTime = 5; public LayerMask visibleLayers = -1; //Event 1 public delegate void HitHandler(AIEventArgs e); public static HitHandler onHit; //Event 2 public delegate void IsDyingHandler(AIEventArgs e); public static IsDyingHandler onIsDying; //Event 3 public delegate void IsDeadHandler(AIEventArgs e); public static IsDeadHandler onIsDead;
//[HideInInspector] public List<Transform> waypoints;
//Additional parameters private float gravityFactor = 2; private float waypointDistance = 5; private float obstacleAvoidanceDistance = 1; private int targetingTolerance = 10;
private bool isfollowingTarget = false; private bool isAttaking = false; private Vector3 lastVisiblePosition = Vector3.zero; private float minimalDistanceStandard; private int currentWaypoint = 0; private bool waypointModus = true; private AnimateState characterAnimationState = AnimateState.idle; private bool isShooting = false; private bool iBeep = false; private bool isWaiting = false; private bool isDead = false; private float shootAnimationLength = 0; private bool isAlive = true; private bool isWalkingToLastPosition = false; enum AnimateState { idle, run, shoot, hit, die }
protected void Awake() { minimalDistanceStandard = minimalDistance; //Mein TargetPoint-Transform zuweisen (Ausgangspunkt fuer alle Raycasts) if (GetComponentInChildren<TargetPointBehaviour>() != null) { TargetPointBehaviour tpScript = GetComponentInChildren<TargetPointBehaviour>(); myTargetPoint = tpScript.gameObject.transform; } else { Debug.LogError("AI Character has no TargetPoint."); }
if (target.gameObject.GetComponentInChildren<TargetPointBehaviour>() != null) { //TargetPoint-Transform des Ziels zuweisen (Ziel aller Raycasts) TargetPointBehaviour otherTpScript = target.gameObject.GetComponentInChildren<TargetPointBehaviour>(); otherTargetPoint = otherTpScript.gameObject.transform; } else { Debug.LogError("Target has no TargetPoint."); } gameObject.rigidbody.useGravity = false; gameObject.rigidbody.freezeRotation = true;
if (spawnPoint == null) { Transform[] allChildren = GetComponentsInChildren<Transform>(); foreach (Transform child in allChildren) { if (child.gameObject.name == "SpawnPoint") { spawnPoint = child; //Debug.Log("spawnpoint found"); } } }
if (spawnPoint != null) { if (spawnPoint.collider != null) { Destroy(spawnPoint.collider); } }
//wenn es noch kein Rigidbody gibt, dann fuegen wir es hier hinzu //Wenn es schon eins gibt, dann erscheint zwar eine Hinweismeldung, das war es aber auch.
fightSound.gameObject = gameObject; hitSound.gameObject = gameObject; dieSound.gameObject = gameObject; fightSound.Init(); hitSound.Init(); dieSound.Init(); }
protected void Start() { //weil der WP-Editor in der Awake-Fkt die Liste fuellt, muessen wir dies erst in Start machen if (idleStart) { DoIdleStart(); }
InitAnimations(); StartCoroutine(Shoot());
}
protected void FixedUpdate() { FindTarget();
if (isAlive) { if (!waypointModus && !isDead) { if (lastVisiblePosition != Vector3.zero) { RotateTo(lastVisiblePosition); Walk(lastVisiblePosition);
//Hinderniss umlaufen CheckBarredWay(lastVisiblePosition); //if (characterAnimationState == AnimateState.idle && !isfollowingTarget)
if (characterAnimationState == AnimateState.idle && !isAttaking && !isWalkingToLastPosition) { waypointModus = true; //Debug.Log("true"); } } else { StopMoving(); } } else {
if (waypoints.Count > 1) { if (waypoints[currentWaypoint] == null) { ClearWaypoints(); } } //StopMoving(); if (waypoints.Count == 0) { SetDynamicWaypoints(); }
if (waypoints.Count > 1) { RotateTo(waypoints[currentWaypoint].position); WaypointWalk(); //Hinderniss umlaufen CheckBarredWay(waypoints[currentWaypoint].position); } }
ObstacleAvoidance();
}
SurfaceDetection(); PlayAnimation(); }
void InitAnimations() { animation.wrapMode = WrapMode.Loop; if (dieAnimation != "") { animation[dieAnimation].wrapMode = WrapMode.ClampForever; animation[dieAnimation].layer = 4; animation.Stop(dieAnimation); //2011-05-28-1 }
if (hitAnimation != "") { animation[hitAnimation].wrapMode = WrapMode.Once; animation[hitAnimation].layer = 3; animation.Stop(hitAnimation); //2011-05-28-1 }
animation[fightAnimation].wrapMode = WrapMode.Once; animation[fightAnimation].layer = 2; shootAnimationLength = animation[fightAnimation].length; animation.Stop(fightAnimation); //2011-05-28-1 animation[idleAnimation].layer = 1; animation.Stop(idleAnimation); //2011-05-28-1 animation[walkAnimation].layer = 1; animation.Stop(walkAnimation); //2011-05-28-1 } IEnumerator Shoot() { bool hasShooted = false; //2011-05-26
if (shootingPause > 0) { float pastTime; while (isAlive) { pastTime = 0; isShooting = false; //2011-05-26 hasShooted = false; //2011-05-26 //if (isfollowingTarget) if (isAttaking && !iBeep == true) { Quaternion toTargetRotation; Vector3 relativePos; //relativePos = lastVisiblePosition - transform.position; ////relativePos = lastVisiblePosition - aiCollider.position; ////toTargetRotation = Quaternion.LookRotation(relativePos); ////toTargetRotation = Quaternion.LookRotation(relativePos); Vector3 lastVisiblePositionTemp = lastVisiblePosition; lastVisiblePositionTemp.y = myTargetPoint.position.y; relativePos = lastVisiblePositionTemp - myTargetPoint.position; toTargetRotation = Quaternion.LookRotation(relativePos);
//Wert 20 kann auch durch eine Variable ersetzt werden //if (EqualRotations(toTargetRotation, transform.rotation, 10))
if (EqualRotations(toTargetRotation, myTargetPoint.rotation, targetingTolerance)) {
//Debug.Log("shoot - isEqualRotations"); isShooting = true;
if (crossFadeAnimations) { animation.CrossFade(fightAnimation); } else { //animation.Play(fightAnimation); animation.PlayQueued(fightAnimation, QueueMode.PlayNow); }
characterAnimationState = AnimateState.idle; yield return new WaitForSeconds(fightEffectsDelay);
if (projectile != null) { GameObject proj; //proj = (GameObject)Instantiate(projectile, spawnPoint.position, gameObject.transform.rotation); //proj = (GameObject)Instantiate(projectile, spawnPoint.position, myTargetPoint.transform.rotation); proj = (GameObject)Instantiate(projectile, spawnPoint.position, spawnPoint.transform.rotation); //Destroy(proj, projectileLifeTime);
if (projectileForce > 0) { proj.rigidbody.AddRelativeForce(Vector3.forward * projectileForce); } } //Debug.Log("shoot"); if (playSound) { fightSound.Play(); }
if (calculationDamage) { //damage by Calculation if (Random.Range(0, 100) <= hitChance) { target.SendMessage("ApplyDamage", Random.Range(minDamage, maxDamage)); } } if (shootAnimationLength < fightEffectsDelay) { yield return new WaitForSeconds(shootAnimationLength - fightEffectsDelay); pastTime = shootAnimationLength; }
if (shootAnimationLength > fightEffectsDelay) { yield return new WaitForSeconds(fightEffectsDelay); pastTime = fightEffectsDelay; //Debug.Log("'Projectile Delay' is shorter than the fight animation lenght"); }
//2011-05-26 -B isShooting = false; if (shootingPause > pastTime) { yield return new WaitForSeconds(shootingPause - pastTime); //hasShooted = true;//2011-05-26 -2 } //2011-05-26 -E hasShooted = true;//2011-05-26 -2 }
}
//2011-05-26 -B //isShooting = false; //if (shootingPause > pastTime) //{ // yield return new WaitForSeconds(shootingPause - pastTime); // //} if (hasShooted == false) { yield return new WaitForSeconds(0.5f); } //2011-05-26 -E } } else { Debug.LogError("Shooting Pause have to be longer than 0 seconds."); }
}
protected void PlayAnimation() { switch (characterAnimationState) { case AnimateState.idle: animation.CrossFade(idleAnimation); break; case AnimateState.run: animation.CrossFade(walkAnimation); break; } }
protected void RotateTo(Vector3 targetPosition) {
//transform.LookAt(targetPosition); Quaternion destRotation; Vector3 relativePos; //relativePos = targetPosition - transform.position;
Vector3 tap; Vector3 trp; tap = targetPosition; //trp = transform.position; trp = myTargetPoint.position; tap.y = 0; trp.y = 0; relativePos = tap - trp;
destRotation = Quaternion.LookRotation(relativePos); //transform.rotation = Quaternion.Slerp(transform.rotation,destRotation, speedRotation *Time.fixedDeltaTime); transform.rotation = Quaternion.Slerp(transform.rotation, destRotation, rotationSpeed );
}
protected void Walk(Vector3 targetPosition) { Vector3 velocity; //Vector3 moveDirection = transform.TransformDirection(Vector3.forward); Vector3 moveDirection = myTargetPoint.TransformDirection(Vector3.forward); //Vector3 delta = targetPosition - transform.position; Vector3 delta = targetPosition - myTargetPoint.position; float magnitude = delta.magnitude;
//if (delta.magnitude > minimalDistance) //if ((delta.magnitude > minimalDistance) && (!isShooting) && (!iBeep) && (!isDead)) if ((magnitude > minimalDistance) && (!isShooting) && (!iBeep) && (isAlive)) { velocity = moveDirection.normalized * movingSpeed ; //animation.CrossFade("run"); characterAnimationState = AnimateState.run; } else { velocity = Vector3.zero; //animation.CrossFade("idle"); if ((!isShooting) && (!iBeep) && (!isDead)) //if ((!isAttaking) && (!iBeep) && (!isDead)) { characterAnimationState = AnimateState.idle; } }
//test-b if ((magnitude > minimalDistance)) {
isWalkingToLastPosition = true;
} else { isWalkingToLastPosition = false; } // test-e rigidbody.velocity = velocity; }
protected void SurfaceDetection() { float tolerance = 0.05f; RaycastHit hit; //Debug.DrawRay(transform.position, -Vector3.up ,Color.red); //Debug.DrawRay(myTargetPoint.position, -Vector3.up * targetPointHeight , Color.red); //if (Physics.Raycast(transform.position, -Vector3.up, out hit, fromSurfaceToCenter, visibleLayers)) //if (Physics.Raycast(transform.position, -Vector3.up, out hit, fromSurfaceToCenter, visibleLayers)) if (Physics.Raycast(myTargetPoint.position, Vector3.down, out hit, targetPointHeight + 2.5f, visibleLayers)) { if (hit.distance < targetPointHeight - tolerance) { //Debug.Log("U hit.distance: " + hit.distance.ToString()); //Debug.Log("gameObject.transform.position.y: " + gameObject.transform.position.y); rigidbody.velocity = rigidbody.velocity + (Vector3.up * gravityFactor ); //rigidbody.velocity = rigidbody.velocity + (Vector3.up * gravityFactor ); } else if (hit.distance > targetPointHeight + tolerance) { //Debug.Log("D hit.distance: " + hit.distance.ToString()); //Debug.Log("gameObject.transform.position.y: " + gameObject.transform.position.y); rigidbody.velocity = rigidbody.velocity + (Vector3.down * gravityFactor ); //rigidbody.velocity = rigidbody.velocity + (Vector3.down * gravityFactor ); } else { if (!isAlive ||(waypointModus== true && waypoints.Count < 2)) { rigidbody.velocity = Vector3.zero; } } } else { rigidbody.velocity = rigidbody.velocity + (Vector3.down * gravityFactor ); //rigidbody.velocity = rigidbody.velocity + (Vector3.down * gravityFactor ); } }
void FindTarget() { if (otherTargetPoint != null) { RaycastHit hit; Ray ray = new Ray(); //ray.origin = transform.position; ray.origin = myTargetPoint.position; //ray.direction = target.position - transform.position; //ray.direction = target.position - myTargetPoint.position; ray.direction = otherTargetPoint.position - myTargetPoint.position;
isfollowingTarget = false; isAttaking = false; //Debug.DrawLine(myTargetPoint.position, otherTargetPoint.position,Color.magenta);
if (Physics.Raycast(ray, out hit, viewDistance, visibleLayers)) { //entweder ist das Object selber mein Zielobject oder aber das Parent von dem getroffenen Object (z.B. bei Collider-Gameobejcts) //if (hit.collider.gameObject.transform == target || (hit.collider.gameObject.transform.parent.gameObject.transform == target)) if (hit.collider.gameObject.transform == target) { //if (isInFieldOfView( target.position)) if (IsInFieldOfView(otherTargetPoint.position)) {
isfollowingTarget = true; //lastVisiblePosition = target.position; lastVisiblePosition = otherTargetPoint.position; waypointModus = false; //dynamic WP if (waypoints.Count > 0) { ClearWaypoints(); //dynamic WP } if (hit.distance <= attakingDistance) { isAttaking = true; } } } else { //Debug.Log("wrong target: " + hit.collider.gameObject.name); } } else { //Debug.Log("no Physics.Raycast detect"); }
if (isfollowingTarget) { minimalDistance = minimalDistanceStandard; } else { minimalDistance = 0.2f; } } else { //dann ist er wohl tot oder hat noch nie existiert //deswegen wechseln wir wieder in den Waypointmodus waypointModus = true; } }
bool IsInFieldOfView(Vector3 destination) { //Vector3 relative = transform.InverseTransformPoint(target); Vector3 relative = myTargetPoint.InverseTransformPoint(destination); float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg; float halfFieldOfView = fieldOfView / 2; if ((angle <= halfFieldOfView) && angle >= (-1) * halfFieldOfView) { return true; } else { return false; } }
void StopMoving() { rigidbody.velocity = Vector3.zero; characterAnimationState = AnimateState.idle; }
protected void WaypointWalk() { if (waypoints.Count > currentWaypoint) { Vector3 targetPosition = waypoints[currentWaypoint].position; Vector3 velocity; //Vector3 moveDirection = transform.TransformDirection(Vector3.forward); Vector3 moveDirection = myTargetPoint.TransformDirection(Vector3.forward); //Vector3 delta = targetPosition - transform.position; Vector3 delta = targetPosition - myTargetPoint.position;
velocity = moveDirection.normalized * movingSpeed ; if (delta.magnitude > 1) { characterAnimationState = AnimateState.run; } else {
if (currentWaypoint < (waypoints.Count - 1)) { currentWaypoint++; } else { currentWaypoint = 0; }
//Wait a random time between 0 and patrolRandomDelay (in seconds) if (waitingMaxTime > 0) { StartCoroutine(Wait(Random.Range(0, waitingMaxTime))); } }
if (isWaiting || iBeep || isDead) { characterAnimationState = AnimateState.idle; velocity = Vector3.zero; }
rigidbody.velocity = velocity; } else { ClearWaypoints(); } }
//dynamic WP void ClearWaypoints() { foreach (Transform tf in waypoints) { if (tf != null) { Destroy(tf.gameObject); } }
waypoints.Clear(); currentWaypoint = 0; }
void SetDynamicWaypoints() { float height = myTargetPoint.position.y;
Vector3 leftPos = Vector3.zero; Vector3 leftPos1 = transform.TransformPoint(Vector3.left * waypointDistance); //Vector3 leftPos1 = myTargetPoint.TransformPoint(Vector3.left * waypointDistance); leftPos1.y = height; float leftPosBarrierDistance1 = 0; //if (IsSomethingBetween(transform.position, leftPos1, out leftPosBarrierDistance1)) if (IsSomethingBetween(myTargetPoint.position, leftPos1, out leftPosBarrierDistance1)) {
Vector3 leftPos2 = transform.TransformPoint(Vector3.left * waypointDistance); //Vector3 leftPos2 = myTargetPoint.TransformPoint(Vector3.left * waypointDistance); leftPos2.y = height; GameObject leftWp2 = new GameObject(); leftWp2.transform.position = leftPos2; leftPos2 = leftWp2.transform.TransformPoint(Vector3.forward * 1); float leftPosBarrierDistance2 = 0;
//if (IsSomethingBetween(transform.position, leftPos2, out leftPosBarrierDistance2)) if (IsSomethingBetween(myTargetPoint.position, leftPos2, out leftPosBarrierDistance2)) {
Vector3 leftPos3 = transform.TransformPoint(Vector3.left * waypointDistance); //Vector3 leftPos3 = myTargetPoint.TransformPoint(Vector3.left * waypointDistance); leftPos3.y = height; GameObject leftWp3 = new GameObject(); leftWp3.transform.position = leftPos3; leftPos3 = leftWp3.transform.TransformPoint(Vector3.back * 1); float leftPosBarrierDistance3 = 0;
//if (IsSomethingBetween(transform.position, leftPos3, out leftPosBarrierDistance3)) if (IsSomethingBetween(myTargetPoint.position, leftPos3, out leftPosBarrierDistance3)) { //wenn alle 3 WPs von etwas versperrt werden // dann waehle ich eins von den aeusseren if (leftPosBarrierDistance2 > leftPosBarrierDistance3) { leftPos = leftPos2; } else { leftPos = leftPos3; } } Destroy(leftWp3);
} else { leftPos = leftPos2; } Destroy(leftWp2);
} else { leftPos = leftPos1; } float barrierDistance = 0; Vector3 surfaceCheck; surfaceCheck = leftPos; surfaceCheck.y -= 10;
if (IsSomethingBetween(leftPos, surfaceCheck, out barrierDistance)) { //nur wenn ein Boden gefunden wird, wird auch ein WP erzeugt leftPos.y -= (barrierDistance - targetPointHeight); CreateWaypoint(leftPos, "wpL"); } else { CreateWaypoint(myTargetPoint.position, "wpL"); }
//Vector3 rightPos; //Vector3 rightPos1 = transform.TransformPoint(Vector3.right * defaultWaypointDistance); //CreateWaypoint(rightPos, "wpR"); Vector3 rightPos = Vector3.zero; Vector3 rightPos1 = transform.TransformPoint(Vector3.right * waypointDistance); //Vector3 rightPos1 = myTargetPoint.TransformPoint(Vector3.right * waypointDistance); rightPos1.y = height; float rightPosBarrierDistance1 = 0; //if (IsSomethingBetween(transform.position, rightPos1, out rightPosBarrierDistance1)) if (IsSomethingBetween(myTargetPoint.position, rightPos1, out rightPosBarrierDistance1)) { Vector3 rightPos2 = transform.TransformPoint(Vector3.right * waypointDistance); //Vector3 rightPos2 = myTargetPoint.TransformPoint(Vector3.right * waypointDistance); rightPos2.y = height; GameObject rightWp2 = new GameObject(); rightWp2.transform.position = rightPos2; rightPos2 = rightWp2.transform.TransformPoint(Vector3.forward * 1); float rightPosBarrierDistance2 = 0;
//if (IsSomethingBetween(transform.position, rightPos2, out rightPosBarrierDistance2)) if (IsSomethingBetween(myTargetPoint.position, rightPos2, out rightPosBarrierDistance2)) {
Vector3 rightPos3 = transform.TransformPoint(Vector3.right * waypointDistance); //Vector3 rightPos3 = myTargetPoint.TransformPoint(Vector3.right * waypointDistance); rightPos3.y = height; GameObject rightWp3 = new GameObject(); rightWp3.transform.position = rightPos3; rightPos3 = rightWp3.transform.TransformPoint(Vector3.back * 1); float rightPosBarrierDistance3 = 0;
//if (IsSomethingBetween(transform.position, rightPos3, out rightPosBarrierDistance3)) if (IsSomethingBetween(myTargetPoint.position, rightPos3, out rightPosBarrierDistance3)) { //wenn alle 3 WPs von etwas versperrt werden // dann waehle ich eins von den aeusseren if (rightPosBarrierDistance2 > rightPosBarrierDistance3) { rightPos = rightPos2; } else { rightPos = rightPos3; } } Destroy(rightWp3);
} else { rightPos = rightPos2; } Destroy(rightWp2); } else { rightPos = rightPos1; }
surfaceCheck = rightPos; surfaceCheck.y -= 10; if (IsSomethingBetween(rightPos, surfaceCheck, out barrierDistance)) { //nur wenn ein Boden gefunden wird, wird auch ein WP erzeugt rightPos.y -= (barrierDistance - targetPointHeight); CreateWaypoint(rightPos, "wpR"); } else { CreateWaypoint(myTargetPoint.position, "wpR"); } }
void CreateWaypoint(Vector3 position, string name) { //GameObject myCube = GameObject.CreatePrimitive(PrimitiveType.Cube); GameObject newWp = new GameObject(); newWp.name = name; newWp.transform.position = position; //myCube.renderer.enabled = false; //Destroy(myCube.collider); waypoints.Add(newWp.transform); }
//dynamic WP ende
public void AddLife(float life) { health += life; }
public void ApplyDamage(float damage) { health -= damage; fieldOfView = 360; if (health <= 0) { StartCoroutine(CharacterDie()); } else { StartCoroutine(CharacterHit()); //CharacterHit(); } }
IEnumerator CharacterHit() { if (hitAnimation != "") { iBeep = true; if (crossFadeAnimations) { animation.CrossFade(hitAnimation); } else { animation.Play(hitAnimation); } if (playSound) { hitSound.Play(); } yield return new WaitForSeconds(0.4f); iBeep = false; }
if (onHit != null) { AIEventArgs e = new AIEventArgs (); e.name = gameObject.name; e.health = health; e.position = gameObject.transform.position; e.rotation = gameObject.transform.rotation; e.tag = gameObject.tag; onHit(e); } }
IEnumerator CharacterDie() { if (!isDead) { isDead = true; isAlive = false; Debug.Log("Play die"); if (dieAnimation != "") {
if (crossFadeAnimations) { animation.CrossFade(dieAnimation); } else { animation.Play(dieAnimation); }
}
if (playSound) { dieSound.Play(); }
yield return new WaitForSeconds(0.4f); if (deathDelayTime == 0) { Destroy(this.gameObject); } else if (deathDelayTime > 0) { Destroy(this.gameObject, deathDelayTime); }
if (onIsDying != null) { AIEventArgs e = new AIEventArgs(); e.name = gameObject.name; e.health = health; e.position = gameObject.transform.position; e.rotation = gameObject.transform.rotation; e.tag = gameObject.tag; onIsDying(e); } } }
void OnDestroy () { if (onIsDead != null && isAlive == false) { AIEventArgs e = new AIEventArgs(); e.name = gameObject.name; e.health = health; e.position = gameObject.transform.position; e.rotation = gameObject.transform.rotation; e.tag = gameObject.tag; onIsDead(e); } } IEnumerator Wait(float seconds) { isWaiting = true; yield return new WaitForSeconds(seconds); isWaiting = false; }
void CheckBarredWay(Vector3 destination) { RaycastHit hit; //Vector3 delta = destination - transform.position; Vector3 delta = destination - myTargetPoint.position; //if (Physics.Raycast(transform.position, delta, out hit, delta.magnitude)) //if (Physics.Linecast(transform.position, destination, out hit, visibleLayers)) if (Physics.Linecast(myTargetPoint.position, destination, out hit, visibleLayers)) { //Wert 1 koennte auch ueber Variable individualisierbar gemacht werden if (hit.distance <= 1) { //Wert 1 koennte auch ueber Variable individualisierbar gemacht werden //if (delta.sqrMagnitude > (1 * 1)) if (delta.sqrMagnitude > 1) { //erstmal anhalten StopMoving(); //Alle Waypoints loeschen(falls es welche gibt), um dann neue zu erzeugen ClearWaypoints(); //Waypoint-Modus aktivieren - die Waypoints selber werden beim naechsten Waypoint-Durchlauf erzeugt. waypointModus = true; //Erzeugt werden die } } } }
bool IsSomethingBetween(Vector3 start, Vector3 destination, out float barrierDistance) { barrierDistance = -1; RaycastHit hit; //Vector3 delta = destination - transform.position; Vector3 delta = destination - myTargetPoint.position; bool result = false; //if (Physics.Raycast(transform.position, delta, out hit, delta.magnitude)) if (Physics.Linecast(start, destination, out hit, visibleLayers)) { barrierDistance = hit.distance; result = true; }
return result; }
bool EqualRotations(Quaternion Rotation1, Quaternion Rotation2, float angleTolerance) { bool isEqual = false;
if (Quaternion.Angle(Rotation1, Rotation2) < angleTolerance) { isEqual = true; }
return isEqual; }
void DoIdleStart() { ClearWaypoints(); //Vector3 startPos = transform.position; Vector3 startPos = myTargetPoint.position; CreateWaypoint(startPos, "wpStart"); }
void ObstacleAvoidance() { Vector3 oaMoveDirection = Vector3.zero; float height = myTargetPoint.position.y; Vector3 leftPos1 = transform.TransformPoint((Vector3.left + Vector3.forward) * obstacleAvoidanceDistance); leftPos1.y = height; float leftPosBarrierDistance1 = 0; //Debug.DrawLine(myTargetPoint.position, leftPos1, Color.blue); if (IsSomethingBetween(myTargetPoint.position, leftPos1, out leftPosBarrierDistance1)) { oaMoveDirection = myTargetPoint.TransformDirection(Vector3.right); } Vector3 rightPos1 = transform.TransformPoint((Vector3.right + Vector3.forward )* obstacleAvoidanceDistance); rightPos1.y = height;
float rightPosBarrierDistance1 = 0; //Debug.DrawLine(myTargetPoint.position, rightPos1, Color.blue); if (IsSomethingBetween(myTargetPoint.position, rightPos1, out rightPosBarrierDistance1)) { if (oaMoveDirection == Vector3.zero || leftPosBarrierDistance1 > rightPosBarrierDistance1) { oaMoveDirection = myTargetPoint.TransformDirection(Vector3.left); } }
if (oaMoveDirection != Vector3.zero) { rigidbody.velocity = rigidbody.velocity + oaMoveDirection.normalized * (movingSpeed) ; } } }
public class AIEventArgs { public string name; public Vector3 position; public Quaternion rotation; public float health; public string tag; }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:43:02 GMT
AI Animations:
using UnityEngine; using System.Collections;
public class AIAnimations : MonoBehaviour {
public AnimationClip idleAnimation; public AnimationClip walkAnimation; public AnimationClip fightAnimation; public AnimationClip hitAnimation; public AnimationClip dieAnimation;
private AIController aiController;
//private string idleAnimationName = "idle"; //private string walkAnimationName = "run"; //private string fightAnimationName = "shoot"; //private string hitAnimationName = ""; //private string dieAnimationName = "";
void Awake() { aiController = gameObject.GetComponentInChildren<AIController>() as AIController;
aiController.idleAnimation = idleAnimation.name; aiController.walkAnimation = walkAnimation.name; aiController.fightAnimation = fightAnimation.name;
if (hitAnimation != null) { aiController.hitAnimation = hitAnimation.name; } if (dieAnimation != null) { aiController.dieAnimation = dieAnimation.name; } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:44:13 GMT
AI Enemy waypoint:
using UnityEngine; using System.Collections; using System; using System.Collections.Generic;
public class AIEnemyWaypointEditor : MonoBehaviour { //public string m_preName = "Waypoint"; //public string m_folderName = "Waypoints"; public string wpFolderName = "Waypoints"; public string wpPreFix = "Waypoint"; private AIController aiController; void Start() { //Waypoint.InitAll(); } void Awake() { aiController = gameObject.GetComponentInChildren<AIController>() as AIController; //FillWaypointList(); }
//void FillWaypointList() //{ // bool found = true; // int counter = 1; // while (found) // { // GameObject go; // string currentName; // currentName = "/" + wpFolderName + "/" + wpPreFix + "_" + counter.ToString(); // go = GameObject.Find(currentName);
// if (go != null) // { // aiController.waypoints.Add(go.transform); // counter++; // } // else // { // found = false; // } // } //}
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:45:31 GMT
Collision Damage:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class CollisionDamageController : MonoBehaviour {
public List<Damage> CollisionDamages;
protected void OnCollisionEnter(Collision collision) { string tag = collision.gameObject.tag;
foreach (Damage cd in CollisionDamages) { if (cd.tag == tag) { int damage = Random.Range(cd.minDamage, cd.maxDamage); gameObject.SendMessage("ApplyDamage", damage); } } }
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:46:23 GMT
Damage:
using UnityEngine; using System.Collections;
[System.Serializable] public class Damage { public string tag = ""; public int minDamage = 10; public int maxDamage = 20; }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:54:15 GMT
Even Listener Example:
using UnityEngine; using System.Collections; //using EnemyAI;
public class EventListenerExample : MonoBehaviour { public GameObject smoke; //public GUIText guiMessages; private string message; private int destroyedCounter = 0; void OnEnable() { AIController.onIsDying += onIsDying; AIController.onIsDead += onIsDead; AIController.onHit += onHit; }
void OnDisable() { AIController.onIsDying -= onIsDying; AIController.onIsDead -= onIsDead; AIController.onHit -= onHit; }
// Use this for initialization void Start () { } // Update is called once per frame void Update () { }
void onIsDying(AIEventArgs e) { message = e.name + " is Dying at position " + e.position + "."; Debug.Log(message); StartCoroutine(ShowMessage(message,1));
if (e.name != "soldier")//2011-05-28-1 { //2011-05-28-1 GameObject smokeObject = Instantiate(smoke, e.position, e.rotation) as GameObject; Destroy(smokeObject, 4); } //2011-05-28-1
destroyedCounter++; }
void onHit(AIEventArgs e) { message = e.name + " is be hit. Current health is " + e.health + "."; Debug.Log(message); StartCoroutine(ShowMessage(message,1)); }
void onIsDead(AIEventArgs e) { message = e.name + " is dead."; Debug.Log(message); StartCoroutine(ShowMessage(message,2)); }
IEnumerator ShowMessage(string text, float seconds) { //guiMessages.text = text; yield return new WaitForSeconds(seconds); //guiMessages.text = ""; } void OnGUI() { GUILayout.Space(20); GUILayout.Label("Destroyed: " + destroyedCounter); } }
|
|
|
Post by Scriptzz on Oct 18, 2013 9:54:55 GMT
Event*
|
|
|
Post by Scriptzz on Oct 18, 2013 9:56:12 GMT
Health Controller Example:
using UnityEngine; using System.Collections;
public class HealthControllerExample : MonoBehaviour { public float health = 100; //public GUIText guiHealth;
protected void OnCollisionEnter(Collision collision) { string tag = collision.gameObject.tag;
ApplyDamage(10);
}
public void ApplyDamage(float damage) { health -= damage; if (health <= 0) { //Debug.Log("die"); } else { //Debug.Log("hit: " + damage); } } void OnGUI() { GUILayout.Label("Player Health: " + health); }
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:57:19 GMT
Shooting Example:
using UnityEngine; using System.Collections;
public class ShootingExample : MonoBehaviour { public GameObject projectile; public Transform spawnPoint; public SoundObject fightSound = new SoundObject(); public SoundObject hitSound = new SoundObject(); public Transform gun; public Transform ammo; public bool calculationDamage = false; //2011-05-26 private Transform myTargetPoint; //2011-05-26 // Use this for initialization void Awake () { fightSound.gameObject = gameObject; fightSound.Init(); hitSound.gameObject = gameObject; hitSound.Init();
//2011-05-26 -B if (GetComponentInChildren<TargetPointBehaviour>() != null) { TargetPointBehaviour tpScript = GetComponentInChildren<TargetPointBehaviour>(); myTargetPoint = tpScript.gameObject.transform; } //2011-05-26 -E } // Update is called once per frame void Update () {
//2011-05-26 -B //if (Input.GetButtonDown("Fire1")) //{ // StartCoroutine(Shoot()); //} if (calculationDamage) { gun.gameObject.active = false; ammo.gameObject.active = false; if (Input.GetButtonDown("Fire1")) { StartCoroutine(Hit()); } } else { gun.gameObject.active = true; ammo.gameObject.active = true; if (Input.GetButtonDown("Fire1")) { StartCoroutine(Shoot()); } } //2011-05-26 -E }
IEnumerator Shoot() { GameObject proj; yield return new WaitForSeconds(0.4f); proj = (GameObject)Instantiate(projectile, spawnPoint.position, spawnPoint.rotation); fightSound.Play(); proj.rigidbody.AddRelativeForce(Vector3.forward * 1000); }
//2011-05-26 -B IEnumerator Hit() { RaycastHit hit; yield return new WaitForSeconds(0.2f); hitSound.Play(); if (Physics.Raycast(myTargetPoint.position, myTargetPoint.TransformDirection(Vector3.forward), out hit, 1.5f)) { hit.transform.gameObject.SendMessage("ApplyDamage", 10, SendMessageOptions.DontRequireReceiver); } }
void OnGUI() { GUILayout.Space(40); calculationDamage = GUILayout.Toggle(calculationDamage, "Beating (Calculation Damage)"); } //2011-05-26 -E
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:58:35 GMT
Sound Object:
using UnityEngine; using System.Collections;
[System.Serializable] public class SoundObject { //ShootSound [SerializeField] private AudioClip soundfile; [SerializeField] private float soundVolume = 1; private AudioSource audioSource; [HideInInspector] public GameObject gameObject; public void Play() { if (soundfile != null) { audioSource.Play(); } }
public void Init() { if (soundfile != null) { //audioSource = gameObject.AddComponent("AudioSource") as AudioSource; audioSource = gameObject.AddComponent("AudioSource") as AudioSource; audioSource.clip = soundfile; audioSource.loop = false; audioSource.volume = soundVolume; audioSource.playOnAwake = false; audioSource.rolloffMode = AudioRolloffMode.Linear; } }
}
|
|
|
Post by Scriptzz on Oct 18, 2013 9:59:40 GMT
Spawn Point Behavior:
using UnityEngine; using System.Collections;
[ExecuteInEditMode] public class SpawnPointBehaviour : MonoBehaviour { public bool lookAtTargetPoint = false; private Transform otherTargetPoint; private AIController aiController;
void Awake() { //renderer.enabled = false;
if (Application.isPlaying) { if (gameObject.collider != null) { Destroy(gameObject.collider); }
if (lookAtTargetPoint) { aiController = transform.parent.gameObject.GetComponentInChildren<AIController>() as AIController; if (aiController.target.gameObject.GetComponentInChildren<TargetPointBehaviour>() != null) { //TargetPoint-Transform des Ziels zuweisen (Ziel aller Raycasts) TargetPointBehaviour otherTpScript = aiController.target.gameObject.GetComponentInChildren<TargetPointBehaviour>(); otherTargetPoint = otherTpScript.gameObject.transform; } } } }
public void Update() { if (Application.isPlaying) { if (lookAtTargetPoint) { gameObject.transform.LookAt(otherTargetPoint); } } }
public void OnDrawGizmos() { if (!Application.isPlaying) { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(gameObject.transform.position, 0.1f); } } }
|
|
|
Post by Scriptzz on Oct 18, 2013 10:00:41 GMT
Target Point Behavior:
using UnityEngine; using System.Collections; //using EnemyAI;
[ExecuteInEditMode] public class TargetPointBehaviour : MonoBehaviour { void Awake() { if (Application.isPlaying) { if (gameObject.collider != null) { Destroy(gameObject.collider); } } } // Use this for initialization void Start() {
}
// Update is called once per frame void Update() {
}
public void OnDrawGizmos() { if (!Application.isPlaying) { if (gameObject.transform.parent.GetComponent<AIController>() != null) { Gizmos.color = Color.green;
AIController aiController = gameObject.transform.parent.GetComponent<AIController>() as AIController; Debug.DrawRay(transform.position, -Vector3.up * aiController.targetPointHeight, Color.red);
} else { Gizmos.color = Color.red; } Gizmos.DrawWireSphere(gameObject.transform.position, 0.1f); } } }
|
|
|
Post by Scriptzz on Oct 18, 2013 10:01:51 GMT
Way point Behavior:
using UnityEngine; using System.Collections;
public class WaypointBehaviour : MonoBehaviour { void Awake() { renderer.enabled = false;
if (gameObject.collider != null) { Destroy(gameObject.collider); } } // Use this for initialization void Start() {
}
// Update is called once per frame void Update() {
} }
|
|
|
Post by Scriptzz on Oct 18, 2013 10:02:54 GMT
Hope they help, if u have a request ill see what i can do.
|
|
|
Post by BathroomsCal on Mar 17, 2019 8:30:44 GMT
Good Night! Sears home remodeling bathroom Brooklyn : <a href=https://bathroom-remodel.club>Handicap bathroom remodel</a>
|
|
|
Post by useptef on May 11, 2019 19:49:15 GMT
Когда у автомобиля стекло трескается то нужна будет замена, то вам в автомобильном сервисе 2 вида Автостекла : оригинальное и послепродажное. И только вам решать какое покупать. Автомобильные стёкла, как и любые другие зап. части авто, делятся на уникальные и неоригинальные. Фирменные стекла изготовляются либо на АВТОЗАВОДЕ, занимающемся выпуском автомобилей, либо у подрядчиков автоконцерна, выпускающих запасные части по лицензии завода, те что напрямую устанавливаются в производимые автомобили. Магазин компания Фуяо продает Авто стёкла по всем городам России. Установкой Автомобильных стёкл Занимается наша фирма. Полировка авто стёкл. Очень часто встречаемым изъяном передового тачки по праву считается потеря автостеклом прозрачности из-за потёртостей, царапин, как правило, от стеклоочистителей. В пользу сохранности пассажиров изготовители делают автомобильные стёкла из довольно мягких видов стекла, что и делает этот недочёт популярным. Частые повреждения лобовых стёкл от автомобиля бывают: незначительные, глубокие, средние повреждения. VBMX Industry Group устанавливает авто стёкла как на отечественные, так и на зарубежные автотранспорт а также на большие автомобили. Фуяо изготовляет автостекла под заказ. Официальный поставщик автостекол в Самаре <a href=https://hobook.ru/>купить лобовое стекло</a>
|
|