using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.Networking;
public class SpellExplosionEffects : MonoBehaviour {
float forceAmount = 50;
Rigidbody r;
float radi;
float spellDuration = 10;
// Use this for initialization
void Awake()
{
radi = GetComponent<SphereCollider>().radius;
Destroy(gameObject, spellDuration);
transform.position = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
}
private void OnTriggerEnter(Collider other) {
if (other == null)
return;
else
if(other.GetComponent<PlayerMove>() != null)
r = other.GetComponent<Rigidbody>();
}
private void FixedUpdate() {
if (r != null){
var direction = Vector3.zero;
if (Vector3.Distance(transform.position, r.position) < radi) {
direction = (transform.position - r.position).normalized;
r.AddRelativeForce(direction * 30, ForceMode.Force);
// r = null;
// Debug.LogError("PLAYER ENTERED SPELL RADIUS");
}
}
}
}
Does anyone know what might be wrong?
It works, it effects the players but sometimes it will repel them instead of pulling them towards the centre of the object.
Sometimes it will only pull players in from one side
This should work if you want to test it just add it to an empty game object with a sphere collider and then add a player which is controlled using the rigid body and when it gets within range it will effect the player but not how I would’ve thought it would.
You see how the blue spell only works sometimes it should pull the player towards the centre slowing down their movement
Do you have more than one player that this could be pulling in? OnTriggerEnter will fire for every player that enters its trigger radius, overwriting R each time. If you have more than 1 “player” that could be affected by this object you would need to change r to a List and keep adding to that last. Then in FixedUpdate iterate over that list, add all the forces, then clear the list. Also you need to set r= null regardless or it will keep adding forces over and over.
Now the reason your getting wonky behaviour is your using AddRelativeForce which treats the force relative to its local rotation. But you using absolute world co-ordinates. So if your spell is turned in any way different from the world forward/up/right then it will act weird. Try changing to just AddForce