How to calculate the distance between array gameObject? - arrays

How to calculate the distance between the generated cubes. The assigned script on the dice only specifies a different speed. How is the distance between the individual instantiate cubes calculated?
Sorry for the bad English, I'm using google trnslator. I'm attaching the code, and I'm a beginner in the unit
public class vehicless : MonoBehaviour
{
[SerializeField] private GameObject[] vehicle;
[SerializeField] private Transform spawnPos;
[SerializeField] private float minTime;
[SerializeField] private float maxTime;
int randomInt;
// Use this for initialization
void Start ()
{
StartCoroutine(SpawnVehicle());
}
// Update is called once per frame
void Update ()
{
}
private IEnumerator SpawnVehicle()
{
int i=1;
while(true)
{
randomInt = Random.Range(0,vehicle.Length);
yield return new WaitForSeconds(Random.Range(minTime,maxTime));
GameObject myPrefabInstance = Instantiate(vehicle[randomInt],spawnPos.position,Quaternion.identity);
var red = myPrefabInstance.gameObject.name; //NAME OBJECT
var namecube = red + i ;
Debug.Log("Name object:"+namecube ) ;
i++;
}
}
}
// float dist = Vector3.Distance(----------);
Thanks for help

If you need to quickly find the distance between 2 objects i suggest you to stock the distance in a dictionary with Tuple Key = (GameObject, GameObject) and Value = float:
Dictionary<(GameObject, GameObject), float>()
public Dictionary<(GameObject, GameObject), float>() calculate(GameObject[] objs)
{
var distanceArray = new Dictionary<(GameObject, GameObject), float>();
for (int i = 0; i < objs.Length; i++)
{
for (int j = i; j < objs.Length; j++)
{
if (i == j)
{
//distance between same obj is 0f
continue;
}
else
{
distanceArray.Add((objs[i], objs[j]), Vector3.Distance(objs[i].transform.position, objs[j].transform.position));
}
}
}
return distanceArray;
}
After you could quickly find the distance between 2 object like this:
if (distanceArray.ContainsKey((obj1, obj2)))
{
distance = distanceArray[(obj1, obj2)];
}
else if (distanceArray.ContainsKey((obj2, obj1)))
{
distance = distanceArray[(obj2, obj1)];
}
else if (obj1 == obj2)
{
distance = 0f;
}
else
{
//Error
}
Your question is not very easy to understand, i just add the way to calculate the distance after each new spawned vehicle:
GameObject myPrefabInstance = Instantiate(vehicle[randomInt],spawnPos.position,Quaternion.identity);
for (int i = 0; i < vehicle.Length; i++)
{
var distance = Vector3.distance(myPrefabInstance.transform.position, vehicle[i].transform.position);
Debug.Log($"Distance: {distance}");
}

I imagine that the cubes have different speeds, objects can be a lot, for example 10.15 cubes and a cube that will have a higher speed to slow down in front of a cube that has a slower speed.

Related

2d array of type Space

I'm trying to make a 9x9 grid of Spaces with 1-10 int values. I'm using the java n-ide app, and am getting a successful compilation, but it's not printing any values.
class Space {
int one = 1;
int two = 2;
...
int ten = 10;
}
class green {
Space[][] board = new Space[9][9];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = new Space();
System.out.println(board[i][j].one);
}
}
}
I think you can just refactor your Space class to just hold a primitive integer value:
class Space {
private int value;
private static final String MSG = "Space values must be between 1 and 10 inclusive";
public Space() { }
public Space(int value) {
// prevent spaces from being created with illegal values
if (value < 1 || value > 10) {
throw new IllegalArgumentException(MSG);
}
this.value = value;
}
public int getValue() {
return value;
}
}
Then, in your consuming class, use the Space class:
class Green {
private Space[][] board = new Space[9][9];
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[i].length; j++) {
// maybe get a value from somewhere and use it below
board[i][j] = new Space();
}
}
}
Regarding your exact question about values not printing, the bigger problem than above is that you don't have any logic for assigning values.

Type Coercion Failed in Action Script 3, getting element from an array

I'm getting this error when I'm getting an element from an array and trying to use some functions on it:
TypeError: Error #1034: Type Coercion failed: cannot convert jogador$
to jogador. at laser/mover_tiro_baixo()
Sorry it's in portuguese, just like the code i'll paste below, but I think you get it: when I retrieve the element from an array it's of type 'jogador$', and if I try to use it as being of 'jogador' it doesn't work. I'm trying to manually force the coercion, as it was trying to convert the object to a DisplayObject (because I'm trying to use the hit test function), but that also didn't work:
TypeError: Error #1034: Type Coercion failed: cannot convert jogador$
to flash.display.DisplayObject. at laser/mover_tiro_baixo()
Code:
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.debugger.enterDebugger;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.display.DisplayObject;
public class laser extends MovieClip {
private var velo: Number;
private var meuPalco: Stage;
var dono: MovieClip;
var inimigoTipo: Number;
var Inimigos: Array;
var Dano: Number;
var Tam:Number;
var i:Number;
public function laser(palco: Stage, posX: Number, posY: Number, velocidade: Number, dano: Number, CimaBaixo: Number, Dono: MovieClip, vetJogadores: Array) {
this.dono = Dono;
this.Dano = dano;
if (getClass(this.dono) == "jogador") {
inimigoTipo = 0;
Inimigos = jogador(this.dono).VetorInimigos;
} else {
inimigoTipo = 1;
Inimigos = vetJogadores;
}
this.meuPalco = palco;
this.velo = velocidade;
this.x = posX;
this.y = posY;
if (CimaBaixo == 1) {
this.addEventListener(Event.ENTER_FRAME, mover_tiro_cima);
} else {
this.addEventListener(Event.ENTER_FRAME, mover_tiro_baixo);
}
meuPalco.addChild(this);
}
public function mover_tiro_cima(evt: Event) {
this.y -= velo;
if (inimigoTipo == 0) { // Dono do tiro é o player
var Tam: Number = Inimigos.length;
var i: Number = 0;
while (i < Tam) {
if (this.hitTestObject(Inimigos[i])) {
inimigo(Inimigos[i]).vida.Diminuir(this.Dano);
}
i++;
}
} else { // Dono do tiro é um inimigo
Tam = Inimigos.length;
i = 0;
while (i < Tam) {
if (this.hitTestObject(Inimigos[i])) {
jogador(Inimigos[i]).vida.Diminuir(this.Dano);
}
i++;
}
}
if (this.y <= 0) {
this.removeEventListener(Event.ENTER_FRAME, mover_tiro_cima);
meuPalco.removeChild(this);
}
}
public function mover_tiro_baixo(evt: Event) {
this.y += velo;
if (inimigoTipo == 0) { // Dono do tiro é o player
Tam = Inimigos.length;
i = 0;
while (i < Tam) {
if (this.hitTestObject(Inimigos[i])) {
inimigo(Inimigos[i]).vida.Diminuir(this.Dano);
}
i++;
}
} else { // Dono do tiro é um inimigo
Tam = Inimigos.length;
i = 0;
while (i < Tam) {
if (this.hitTestObject(Inimigos[i])) {
jogador(Inimigos[i]).vida.Diminuir(this.Dano);
}
i++;
}
}
if (this.y <= 0) {
this.removeEventListener(Event.ENTER_FRAME, mover_tiro_baixo);
meuPalco.removeChild(this);
}
}
static function getClass(obj: Object): String {
return String(Class(getDefinitionByName(getQualifiedClassName(obj))));
}
}
}
The error happens everytime the laser tests to see if it's hitting an enemy (hittest) in its functions. mover_tiro_baixo() moves the shot down.
Thanks people!
Edit: The way I create the arrays:
var player1:jogador = new jogador(stage,350,700,10,3,1);
var Jogadores:Array = [jogador];
player1.setJogadores(Jogadores);
var inimigo1:et = new et(stage,100,200,Jogadores);
var inimigo2:et = new et(stage,200,100,Jogadores);
var inimigo3:et = new et(stage,350,450,Jogadores);
var todosInimigos:Array = [inimigo1,inimigo2,inimigo3];
player1.DefinirInimigos(todosInimigos);
I've checked some other stack overflow questions that have similar type conversion errors. Most of the other people with a similar problem were actually filling their array with a Class, rather than objects that were instances of a Class. Are you filling those arrays like this?
for(var i:int = 0; i < 10; i++){
Inimigos.push(jogador); //incorrect
}
If so, that is the reason the problem is happening. This is the correct way to do it:
for(var i:int = 0; i < 10; i++){
Inimigos.push(new jogador()); //correct
}
EDIT:
In the new code you added to the first post, this line seems to be the problem:
var Jogadores:Array = [jogador]; //jogador is a class
Flash Actionscript Arrays cannot be "initialized" to only be able to contain a specific type of object. Actionscript Vectors are capable of that, but not Arrays. That line posted above initializes an array in which the first element is a class, not an object.

core-plot Mixing CPTScatterPlotInterpolationCurved and CPTScatterPlotInterpolationLinear

I need to be able to draw sequential line segments that have the same Y Coordinate with CPTScatterPlotInterpolationLinear and ones that do not with CPTScatterPlotInterpolationCurved.
As CPTScatterPlotInterpolationCurved draws all lines curved. I am currently doing this by adding multiple plots.
public List<CorrectedGraphPoints> GetCorrectDataPoints(List<PointF> dataSource)
{
int lastIndex = 0;
bool shouldLoop = true;
CPTScatterPlotInterpolation interpolation = CPTScatterPlotInterpolation.Curved;
List<CorrectedGraphPoints> OuterList = new List<CorrectedGraphPoints> ();
if (dataSource [0].Y == dataSource [1].Y)
interpolation = CPTScatterPlotInterpolation.Linear;
while (lastIndex+1 != dataSource.Count) {
OuterList.Add (new CorrectedGraphPoints (interpolation));
while (shouldLoop)
{
OuterList[OuterList.Count -1].Add(dataSource[lastIndex]);
if ((lastIndex + 1) < dataSource.Count) {
if (interpolation == CPTScatterPlotInterpolation.Linear) {
if (dataSource [lastIndex].Y != dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Curved;
shouldLoop = false;
break;
}
}
if (interpolation == CPTScatterPlotInterpolation.Curved) {
if (dataSource [lastIndex].Y == dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Linear;
shouldLoop = false;
break;
}
}
}
else {
shouldLoop = false;
break;
}
if (shouldLoop)
lastIndex++;
}
shouldLoop = true;
}
return OuterList;
}
public class CorrectedGraphPoints
{
private List<PointF> points;
public List<PointF> Points { get { return points; } }
private CPTScatterPlotInterpolation interpolation;
public CPTScatterPlotInterpolation Interpolation { get { return interpolation; } }
public CorrectedGraphPoints(CPTScatterPlotInterpolation interpolation)
{
this.interpolation = interpolation;
points = new List<PointF> ();
}
public void Add(PointF point)
{
points.Add (point);
}
}
However creating multiple plots that use fill slows the app down tremendously. I was wondering if I could limit how much I do this? I haven't been able to find a way to change the interpolation for a section?? IS this an just an issue with core plot or is it something wrong with my logic or code?
Another possible solution would be to add additional points to your data to draw the curved sections. This would allow you to use only one plot. The number of additional points needed will depend on several factors including the size of the plot and the line style used to draw the line.

Get value from an Arraylist of Objects - processing

I'm making a virtual pet game, and I am now trying to include hunger, however I'm not sure how to make the eat function work. I am trying to make it decrease through the addition of the nutrition value of an item of food. This value is in an object that is stored in an arraylist.
Is there a way to reference
int nutrition(int eaten) {
nutrition = nutrition - eaten;
return nutrition;
(int eaten will be passed in later)
inside
ArrayList items;
void setup() {
items = new ArrayList();
}
void draw() {
for (int i = items.size() - 1; i >=0; i --) {
Food food = (Food) items.get(i);
food.display();
if (food.finished()) {
items.remove(i);
}
}
}
void mouseClicked() {
items.add(new Food(mouseX, mouseY, 1));
}
((Food)items.get(i)).nutrition();
http://www.java-forums.org/new-java/2370-how-return-object-arraylist.html
I've tried to use this, but Processing is unable to find i. I believe this to be because i does not exist in the class, only in the main sketch. If this is so, I will find a way to place i into the method. Maybe using return.
I would appreciate the knowledge if someone was aware of a better way to do this.
CODE
Creature creature;
ArrayList items;
Hand hand;
String data[];
int gameInfo[];
int tempData[];
boolean haveFood;
void setup() {
size(100, 100);
smooth();
noCursor();
String data[] = loadStrings("save.txt");
String[] tempData = split(data[0], ',');
gameInfo = int(tempData);
for (int i = 0; i < data.length; i++) {
creature = new Creature(gameInfo[0], gameInfo[1], gameInfo[2], gameInfo[3]);
haveFood = false;
hand = new Hand();
items = new ArrayList();
}
}
void draw() {
background(255);
for (int i = items.size() - 1; i >=0; i --) {
Food food = (Food) items.get(i);
food.display();
if (food.finished()) {
items.remove(i);
}
}
creature.whatWant();
creature.whatDo(haveFood);
hand.draw();
}
void mouseClicked() {
items.add(new Food(mouseX, mouseY, 1));
haveFood = true;
}
class Creature {
int hunger;
int age;
int gender;
int asleep;
boolean idle;
char want;
char request;
Creature(int _gender, int _age, int _hunger, int _asleep) {
gender = _gender;
age = _age;
hunger = _hunger;
asleep = _asleep;
idle = true;
}
void whatWant() {
if (hunger == 50) {
want = 'H';
}
}
void whatDo(boolean food) {
if (idle == true) {
switch(want) {
case 'H':
if (food == true) {
creature.eat();
}
else
request = 'F';
ask();
}
}
else
{
println("IDLE");
}
}
void ask() {
if (request == 'F') {
println("HUNGRY");
}
}
void eat() {
println("EAT");
((Food)items.get(i)).nutrition();
}
}
class Food {
float posX;
float posY;
int nutrition;
Food(float _posX, float _posY, int rating) {
posX = _posX;
posY = _posY;
nutrition = rating;
}
void display() {
rect(posX, posY, 10, 10);
}
boolean finished() {
if (nutrition < 0) {
return true;
}
else {
return false;
}
}
int nutrition(int eaten) {
nutrition = nutrition - eaten;
return nutrition;
}
}
class Hand {
int posX;
int posY;
Hand() {
posX = mouseX;
posY = mouseY;
}
void draw() {
rectMode(CENTER);
point(mouseX, mouseY);
}
}
Where save.txt is a txt file with 1,1,50,1,1.
Unfortunately I can't provide a nice detailed answer. There are quite a few confusing things with the structure of your project and it's code.
In the meantime, you had a syntax error in the Creature's eat() function.
Try this:
void eat() {
println("EAT");
//((Food)items.get(i)).nutrition();
for(int i = 0 ; i < items.size(); i++){
Food yummy = (Food)items.get(0);
yummy.nutrition(hunger);
}
}
The above works because items is declared at the top and therefore visible through out the scope of the whole sketch(global in other words). I'm not sure if this is intentional or what relationship you plan between creatures and food.
The above can be written in a lazier(but less common/obvious) way like so:
void eat() {
println("EAT");
//((Food)items.get(i)).nutrition();
for(Object yummy : items) ((Food)yummy).nutrition(hunger);
}
I assume the creature will be fed based on how hungry it.
At some point the creature should be full I suppose,
so you would also update the creature's hungry property based on the nutrition
it gets from food, etc.
Also, just to test, I've added very nutritious food :P
items.add(new Food(mouseX, mouseY, 10000));

Objects stuck at top of stage and won't fall down

I am using math.random to randomly drop objects from the top of the stage. I had it working with one object. But as I wanted to increase the number to 6 objects, I added the following code: But I am "stuck" and so are the 6 objects at the top of the stage. What am I doing wrong here? I appreciate the help.
private function bombInit(): void {
roachBombArray = new Array();
for (var i:uint =0; i < numBombs; i++) {
roachBomb= new RoachBomb();
roachBomb.x = Math.random() * stage.stageWidth;
roachBomb.vy = Math.random() * 2 -1;
roachBomb.y = -10;
addChild(roachBomb);
roachBombArray.push(roachBomb);
}
addEventListener(Event.ENTER_FRAME, onEntry);
}
private function onEntry(event:Event):void {
for (var i:uint = 0; i< numBombs; i++) {
var roachBomb = roachBombArray[i];
vy += ay;
roachBombArray[i] += vy;
if (roachBombArray[i] > 620) {
removeChild(roachBombArray[i]);
removeEventListener(Event.ENTER_FRAME, onEntry);
You are trying to add the velocity to the RoachBomb rather than to the RoachBomb y position.
roachBombArray[i] += vy;
should be
roachBombArray[i].y += vy;
Additionally you create a local variable:
var roachBomb = roachBombArray[i];
but you never manipulate it.
Perhaps you meant to do something like this?
var roachBomb:RoachBomb = roachBombArray[i]; // I added the type to the local variable
roachBomb.vy += ay;
roachBomb.y += vy; // Manipulate the local variable
if (roachBomb.y > 620) {
removeChild(roachBomb);
}
You're removing your enterFrame listener when the first bomb goes off the bottom, at which point you're no longer listening for ENTER_FRAME events and updating any of your bombs.
You don't want to remove this listener until you're done animating ALL the bombs.
UPDATE: How I would expect things to look, incorperating Ethan's observation that you ought to use the local roachBomb that you declare...
public class BombDropper extends Sprite {
private static const GRAVITY:int = 1; // Set gravity to what you want in pixels/frame^2
private static const BOTTOM_OF_SCREEN:int = 620;
private var numBombs:int = 6;
private var roachBombArray:Array;
// ... constructor and other class stuff here
private function bombInit(): void
{
roachBombArray = new Array();
for (var i:int =0; i < numBombs; ++i)
{
var roachBomb:RoachBomb = new RoachBomb();
roachBomb.x = Math.random() * stage.stageWidth;
roachBomb.vy = Math.random() * 2 -1;
roachBomb.y = -10;
this.addChild(roachBomb);
roachBombArray.push(roachBomb);
}
this.addEventListener(Event.ENTER_FRAME, onEntry);
}
private function onEntry(event:Event):void
{
for each ( var roachBomb:RoachBomb in roachBombArray)
{
roachBomb.vy += GRAVITY;
roachBomb.y += vy;
if (roachBomb.y > BOTTOM_OF_SCREEN)
{
this.removeChild(roachBomb);
roachBombArray.splice(roachBombArray.indexOf(roachBomb),1);
if (roachBombArray.length == 0)
{
this.removeEventListener(Event.ENTER_FRAME, onEntry);
}
}
}
}
}

Resources