Unknown reason for "ArgumentOutOfRangeException: Argument is out of range. Parameter name: index" exception - list

I am making a Unity game where the player is collecting data about aliens.
Therefor the player points on the alien and uses something like a camera.
Camera --> shoots Ray --> Ray returns all needed data attached to the script on the alien-gameobject
void ShootRay()
{
RaycastHit hitInfo; // stores information about hitted object
if (Physics.Raycast (transform.position, transform.forward, out hitInfo, maxRaycastRange, 1 << LayerMask.NameToLayer("creature"))) // out hitInfo = Unity puts information in the variable hitInfo
{
// UI alerts and collecting dna
if (hitInfo.distance <= photoRaycastRange)
{
distanceInfo.text = "scanning_genome";
if (hitInfo.collider.gameObject.GetComponent<EnemyAI> ().dna_collected == false) {
if (dna_percent_0_to_1 < 1)
{
calming_dna_scan_circle = false;
distanceInfo.text = "scanning_genome";
dna_percent_0_to_1 += Time.deltaTime * dna_scanSpeed;
dna_collect_circle.fillAmount = dna_percent_0_to_1;
}
else if (dna_percent_0_to_1 >= 1)
{
// adding info of creature to database
if (hitInfo.collider.gameObject.GetComponent<EnemyAI> ().raceIndex == 1)
{
if (!raceOneWasAdded)
{
BestiariumData.scannedSpecies.Add (hitInfo.collider.gameObject);
raceOneWasAdded = true;
}
BestiariumData.dnaBar_1 += 0.25f;
The mentioned database is simply a class called BestiariumData with:
public static List<GameObject> scannedSpecies = new List<GameObject> ();
public static List<float> savedDNAFillRates = new List<float> ();
public static float dnaBar_1 = 0;
public static float dnaBar_2 = 0;
public static float dnaBar_3 = 0;
public static float dnaBar_4 = 0;
public static float dnaBar_5 = 0;
public static float dnaBar_6 = 0;
public static float dnaBar_7 = 0;
public static float dnaBar_8 = 0;
}
I'm having a menu where the player can check which aliens he/she already has collected data. The name of the alien is displayed (Monster One, ...) and a progress bar for how many alien individuals the player has scanned.
THE PROBLEM:
if I try to assign the NAME of the status bar if throws the ArgumentOutOfRangeException: Argument is out of range. Parameter name: index exception. I am doing this by setting a bool in another script to true.
public List<GameObject> monsterButtons = new List<GameObject>();
public static bool nameButtons = false;
// Update is called once per frame
void LateUpdate ()
{
if (nameButtons)
{
for (int buttonIndex = monsterButtons.Count; buttonIndex > 0; buttonIndex--)
{
monsterButtons [buttonIndex].GetComponentInChildren<Text> ().text = BestiariumData.scannedSpecies [buttonIndex].name;
}
}
}
Thank you for your help.

Button index gives the count of your list. So say your list contains 10 items, count will be 10.
However a list's index starts at 0, not 1.
So when you try to access monsterButtons [buttonIndex] for the first time, you are calling index 10, which means item 11. This does not exist so throws your error.
To fix, add "-1" to your index asigning:
for (int buttonIndex = monsterButtons.Count -1; buttonIndex >= 0; buttonIndex--)
{
monsterButtons [buttonIndex].GetComponentInChildren<Text> ().text = BestiariumData.scannedSpecies [buttonIndex].name;
}

Related

How do i perform operations on a structures field?

I im currently having an issue with when performing an operation with my structure.
On form load, I am loading a comma delimited file with 6 indexes then using a 2d array i display the structured list's field to a grid view cell.
In the last for loop, perform the operation using my total field?
{
public partial class Form1 : Form
{
public struct Costomers
{
public string firstN;
public string lastN;
public string address;
public string item;
public double price;
public int quantity;
public double total;
}
public Form1()
{
InitializeComponent();
}
List<Costomers> consumers = new List<Costomers>();
private void Form1_Load(object sender, EventArgs e)
{
var inputfile = File.ReadAllLines("customers.txt");
for (int i = 0; i < inputfile.Length; i++)
{
var SplitArr = inputfile[i].Split(',');
// next declare a new instace of costomers
Costomers ConsumerInfo = new Costomers();
// the ConsumerInfo object now contains all of the fields i declared in the structer.
// next i want to access the Objects fields and assign them
ConsumerInfo.firstN = SplitArr[0];
ConsumerInfo.lastN = SplitArr[1];
ConsumerInfo.address = SplitArr[2];
ConsumerInfo.item = SplitArr[3];
ConsumerInfo.price = Convert.ToDouble(SplitArr[4]);
ConsumerInfo.quantity = Convert.ToInt32(SplitArr[5]);
//ConsumerInfo.total = consumers[i].price * consumers[i].quantity;
consumers.Add(ConsumerInfo);
}
// Next i need to disply each field in the grid view
// i will resue my code from section F to do this.
for (int i = 0; i < consumers.Count; i++)
{
dgInfo.Rows.Add();
dgInfo[0, i].Value = consumers[i].firstN;
dgInfo[1, i].Value = consumers[i].lastN;
dgInfo[2, i].Value = consumers[i].address;
dgInfo[3, i].Value = consumers[i].item;
dgInfo[4, i].Value = consumers[i].price;
dgInfo[5, i].Value = consumers[i].quantity;
}
// next in a seperat for loop i need too mutiply the price by the quantity
for (int i = 0; i < consumers.Count; i++)
{
Costomers totalPrice = new Costomers();
totalPrice.total = consumers[i].price * consumers[i].quantity;
dgInfo[6,i].Value = totalPrice.total;
}
}
}
}```
Second, because the file i load does not contain a index for total; how to i display the total in its own column?
Text file as shown below:
The, Batman, 123 Gotham Drive, bat belt, 193.82,17
The, Joker, 12432 Joker Way, Bat Spray, 19.99, 1022
Cat, Women, 8787 Meow St., Kibbles, 9.99, 4700
The, Penguin, 17 Waddel Ave., pointy cigarettes, 24.99, 51700
sidekick, Robin, 123 Gotham Drive, junior bat belt, 67.80, 10000
Adam, West, 1782 Hollywood Dr., hasbeen kit, 10305018.18, 1

How to know file is from internal or external storage in android?

I want to know how to figure out file path is from internal or external storage.
I want to delete a file. Before deleting it i want to check whether it is from internal memory or external.
if file is from internal storage then i can simply delete it like this
file.delete();
But if file is from external storage (sdcard). Then i would first check permission then delete it through storage access framework.
I'm currently doing like this.
File selectedFile = Constant.allMemoryVideoList.get(fPosition).getFile().getAbsoluteFile();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (???????????? check if file is not from internal storage ???????????) {
List<UriPermission> permissions = getContentResolver().getPersistedUriPermissions();
if (permissions != null && permissions.size() > 0) {
sdCardUri = permissions.get(0).getUri();
deleteFileWithSAF();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select external storage directory (e.g SDCard)")
.setMessage("Due to change in android security policy it is not possible to delete or rename file in external storage without granting permission")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// call document tree dialog
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
} else {
deleteFile();
}
} else {
deleteFile();
}
deleteFileWithSAF()
private void deleteFileWithSAF() {
//First we get `DocumentFile` from the `TreeUri` which in our case is `sdCardUri`.
DocumentFile documentFile = DocumentFile.fromTreeUri(this, sdCardUri);
//Then we split file path into array of strings.
//ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "myImage.jpg"}
// There is a reason for having two similar names "MyFolder" in
//my exmple file path to show you similarity in names in a path will not
//distract our hiarchy search that is provided below.
String[] parts = (selectedFile.getPath()).split("\\/");
// findFile method will search documentFile for the first file
// with the expected `DisplayName`
// We skip first three items because we are already on it.(sdCardUri = /storage/extSdCard)
for (int i = 3; i < parts.length; i++) {
if (documentFile != null) {
documentFile = documentFile.findFile(parts[i]);
}
}
if (documentFile == null) {
// File not found on tree search
// User selected a wrong directory as the sd-card
// Here must inform user about how to get the correct sd-card
// and invoke file chooser dialog again.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select root of external storage directory (click SELECT button at bottom)")
.setMessage("Due to change in android security policy it is not possible to delete or rename file in external storage without granting permission")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// call for document tree dialog
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
} else {
// File found on sd-card and it is a correct sd-card directory
// save this path as a root for sd-card on your database(SQLite, XML, txt,...)
// Now do whatever you like to do with documentFile.
// Here I do deletion to provide an example.
if (documentFile.delete()) {// if delete file succeed
// Remove information related to your media from ContentResolver,
// which documentFile.delete() didn't do the trick for me.
// Must do it otherwise you will end up with showing an empty
// ImageView if you are getting your URLs from MediaStore.
getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(selectedFile)));
// Methods.removeMedia(this,selectedFile.getPath());
if (deleteSingleFileCall){
Constant.allMemoryVideoList.remove(videoPosition);
adapter.notifyItemRemoved(videoPosition);
deleteSingleFileCall = false;
}
/*update the playback record to
* getFileName() contain file.getName()*/
for (int i = 0; i < Constant.filesPlaybackHistory.size(); i++) {
if ((selectedFile.getName()).equals(Constant.filesPlaybackHistory.get(i).getFileName())) {
Constant.filesPlaybackHistory.remove(i);
break;
}
}
//save the playback history
Paper.book().write("playbackHistory", Constant.filesPlaybackHistory);
}
}
}
This is how i load files of both internal and external storage.
StorageUtil is library https://github.com/hendrawd/StorageUtil
String[] allPath = StorageUtil.getStorageDirectories(this);
private File directory;
for (String path: allPath){
directory = new File(path);
Methods.load_Directory_Files(directory);
}
All Loaded files in following arraylist.
//all the directory that contains files
public static ArrayList<File> directoryList = null;
//list of all files (internal and external)
public static ArrayList<FilesInfo> allMemoryVideoList = new ArrayList<>();
FilesInfo: Contain all info about file like thumbnail, duration, directory, new or played before, if played then last playback position etc
LoadDirectoryFiles()
public static void load_Directory_Files(File directory) {
//Get all file in storage
File[] fileList = directory.listFiles();
//check storage is empty or not
if(fileList != null && fileList.length > 0)
{
for (int i=0; i<fileList.length; i++)
{
boolean restricted_directory = false;
//check file is directory or other file
if(fileList[i].isDirectory())
{
for (String path : Constant.removePath){
if (path.equals(fileList[i].getPath())) {
restricted_directory = true;
break;
}
}
if (!restricted_directory)
load_Directory_Files(fileList[i]);
}
else
{
String name = fileList[i].getName().toLowerCase();
for (String ext : Constant.videoExtensions){
//Check the type of file
if(name.endsWith(ext))
{
//first getVideoDuration
String videoDuration = Methods.getVideoDuration(fileList[i]);
long playbackPosition;
long percentage = C.TIME_UNSET;
FilesInfo.fileState state;
/*First check video already played or not. If not then state is NEW
* else load playback position and calculate percentage of it and assign it*/
//check it if already exist or not if yes then start from there else start from start position
int existIndex = -1;
for (int j = 0; j < Constant.filesPlaybackHistory.size(); j++) {
String fListName = fileList[i].getName();
String fPlaybackHisName = Constant.filesPlaybackHistory.get(j).getFileName();
if (fListName.equals(fPlaybackHisName)) {
existIndex = j;
break;
}
}
try {
if (existIndex != -1) {
//if true that means file is not new
state = FilesInfo.fileState.NOT_NEW;
//set playbackPercentage not playbackPosition
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(fileList[i].getPath());
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
retriever.release();
int duration = Integer.parseInt(time);
playbackPosition = Constant.filesPlaybackHistory.get(existIndex).getPlaybackPosition();
if (duration > 0)
percentage = 1000L * playbackPosition / duration;
else
percentage = C.TIME_UNSET;
}
else
state = FilesInfo.fileState.NEW;
//playbackPosition have value in percentage
Constant.allMemoryVideoList.add(new FilesInfo(fileList[i],
directory,videoDuration, state, percentage, storageType));
//directory portion
currentDirectory = directory.getPath();
unique_directory = true;
for(int j=0; j<directoryList.size(); j++)
{
if((directoryList.get(j).toString()).equals(currentDirectory)){
unique_directory = false;
}
}
if(unique_directory){
directoryList.add(directory);
}
//When we found extension from videoExtension array we will break it.
break;
}catch (Exception e){
e.printStackTrace();
Constant.allMemoryVideoList.add(new FilesInfo(fileList[i],
directory,videoDuration, FilesInfo.fileState.NOT_NEW, C.TIME_UNSET, storageType));
}
}
}
}
}
}
Constant.directoryList = directoryList;
}
Image So reader could easily understand what is going on.

std::map pass by reference Pointer to Object

I'm coding a plugin for XPLANE10 which gets a MSG from ROS.
My IDE is QTcreator 4.1.0 based QT 5.7.0 for Ubuntu 64 Bit. I would like to use C++11 Standards
My code explained
The main initializes ROS and creates a map -> container.
ROS spins in a loop till my GUI sends a MSG where my AirPlane should fly.
The MSG contains 3 floats(phi, theta, psi) where "phi" is the AirPlane ID, theta contains the ID for my ETA(Estimated Time of Arrival)
and psi contains the ID for my pose All of the IDs are saved in the ParameterServer(lookuptable).
So at the beginning i look up the activeAirplanes which returns a vector . I would like to store them in a map where the key is the AirCraft ID and the second param is an instance of the Object.
So i have initialized the for example(looked in container while debugging):
[0] first = 1 // Airplane ID1
[0] second = new CObject(freq)
[1] first = 2 // Airplane ID2
[1] second = new CObject(freq)
If i get a MSG from GUI
phi = 1
theta=2
psi=3
,
ROS will callback
MSG(....std::map<i32, CObject> &container)
// if phi is 1 so use the mapkey 1 and trigger the method do_stuff from CObject
do_stuff(phi, theta, psi,freq)
I would like to call the in a function from main
int getPlanes(std::map<i32,CObject>& container)
{
...
getActiveAirplanesFromServer(activePlanes);
}
First Question:
How do i pass the container to my callback?
Second Question:
How do i parallelize do_stuff() so my callback will return to main and i'm able to command more aircrafts while the others are calculated?
Third Question:
How would be the correct syntax for getPlanes to pass the container by reference so getPlanes() can edit it?
Fourth Question:
Is there a difference between
std::map<i32,CObject*> map
std::map<i32,CObject>* map
and
std::map<i32,CObject*>::iterator it=container->begin();
std::map<i32,CObject*>::iterator* it=container->begin();
If yes, what do i want ? #4Solved
// I have to edit stuff 'cause of some restrictions in my company.
#include "Header.h"
int main()
{
f64 freq = 10;
std::map<i32, CObject>* container;
std::map<i32,CObject>::iterator* it=container->begin();
// ROS
if(!ros::isInitialized())
{
int rosargc = 0;
char** rosargv = NULL;
ros::init(rosargc, rosargv, "MainNode");//), ros::init_options::AnonymousName);
}
else
{
printf("Ros has already been initialized.....\n");
}
ros::NodeHandle* mainNodeHandle=new ros::NodeHandle;
ros::AsyncSpinner spinner(2);
ParameterServer * ptrParam= new ParameterServer(mainNodeHandle);
ros::Subscriber airSub=mainNodeHandle->subscribe<own_msgs::ownStruct>("/MSG",
1000,
boost::bind(MSG,
_1,
freq,
container));
std::vector<i32> activePlanes;
i32 retVal=0;
retVal += ptrParam-> ParameterServer::getActiveAirplanesFromServer(activePlanes);
if (retVal == 0 && activePlanes.size()>0)
{
for (u32 j =0; j <activePlanes.size(); j++)
{
container->insert (std::pair<i32,CObject> (activePlanes[j] , new CObject(freq)));
}
}
while (ros::ok())
{
spinner.start(); //spinnt sehr viel :-)
ros::waitForShutdown ();
}
std::cout<<"ENDE"<<std::endl;
int retval = 1;
return retval;
}
void MSG(const own_msgs::ownStruct<std::allocator<void> >::ConstPtr &guiMSG,
f64 freq,
std::map<i32, CObject> &container)
{
if ((guiMSG->phi != 0) && (guiMSG->theta != 0) && (guiMSG->psi != 0))
{
std::string alpha = std::to_string(guiMSG->phi)+std::to_string(guiMSG->theta)+to_string(guiMSG->psi);
container.at(guiMSG->phi) -> do_stuff(guiMSG->phi,guiMSG->theta,guiMSG->psi, freq);
}
else
{
std::cout<<" Did not receive anything\n"<<endl;
}
}
void do_stuff(...)
{
//copy the IDs to private Member of this single Object
//setROS() for this single Object
//callback the current AC pose via ID from XPLANE
//callback the wished AC pose via ID from ParamServer
// do some calculations for optimum flight path
// publish the Route to XPlane
}
EDIT::
Problem is i get it to compile now and if debug it and set a breakpoint at :
void MSG(const own_msgs::ownStruct<std::allocator<void> >::ConstPtr &guiMSG,f64 freq,std::map<i32, CObject*> &container)
{
..
/*->*/ container.at(guiMSG->)...
}
The Container remains empty.
So i read some stuff about pointers and i saw my errors..
I confused * and &
if i want to pass the adress of a variable i have to write like
int main()
{
int a = 0;
AddTwo(&a)
cout<<a<<endl; // Output: 2
}
void AddTwo(int* a)
{
a+=2;
}

OSMdroid bounds marker

////OSMdroid centered on the markers////
I add markers, I need to map the maximum increases or decreases in such a way that all markers were visible
my code:
public class mapcode extends Activity {
globalvar appState;
int stats=0;
private MapView mapView;
private IMapController mapController;
private SimpleLocationOverlay mMyLocationOverlay;
private ScaleBarOverlay mScaleBarOverlay;
ItemizedIconOverlay<OverlayItem> currentLocationOverlay;
DefaultResourceProxyImpl resourceProxy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.map);
appState = ((globalvar) getApplicationContext());
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setTileSource(TileSourceFactory.MAPNIK);
// mapView.setBuiltInZoomControls(true); //кнопка ZOOM +-
mapView.setMultiTouchControls(true);
mapController = this.mapView.getController();
mapController.setZoom(2);
this.mMyLocationOverlay = new SimpleLocationOverlay(this);
this.mapView.getOverlays().add(mMyLocationOverlay);
this.mScaleBarOverlay = new ScaleBarOverlay(this);
this.mapView.getOverlays().add(mScaleBarOverlay);
// this.mapView
/////////////////
resourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
GeoPoint currentLocation = new GeoPoint(55.860863,37.115046);
GeoPoint currentLocation2 = new GeoPoint(63.557413,-156.102119);
OverlayItem myLocationOverlayItem = new OverlayItem("Here", "Current Position", currentLocation);
Drawable myCurrentLocationMarker = this.getResources().getDrawable(R.drawable.a);
myLocationOverlayItem.setMarker(myCurrentLocationMarker);
// myLocationOverlayItem.setMarkerHotspot(HotspotPlace.CENTER); //no working/
final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
items.add(myLocationOverlayItem);
myLocationOverlayItem = new OverlayItem("Here", "Current Position", currentLocation2);
myCurrentLocationMarker = this.getResources().getDrawable(R.drawable.a);
myLocationOverlayItem.setMarker(myCurrentLocationMarker);
// myLocationOverlayItem.setMarkerHotspot(HotspotPlace.CENTER); // no working
items.add(myLocationOverlayItem);
currentLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
return true;
}
public boolean onItemLongPress(final int index, final OverlayItem item) {
return true;
}
}, resourceProxy);
this.mapView.getOverlays().add(this.currentLocationOverlay);
}
I added two markers, but only one is visible:
and I need to osmdroid is centered and immediately showed both marker
I think you want something like this:
int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLong = Integer.MIN_VALUE;
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
for (OverlayItem item : items) {
GeoPoint point = item.getPoint();
if (point.getLatitudeE6() < minLat)
minLat = point.getLatitudeE6();
if (point.getLatitudeE6() > maxLat)
maxLat = point.getLatitudeE6();
if (point.getLongitudeE6() < minLong)
minLong = point.getLongitudeE6();
if (point.getLongitudeE6() > maxLong)
maxLong = point.getLongitudeE6();
}
BoundingBoxE6 boundingBox = new BoundingBoxE6(maxLat, maxLong, minLat, minLong);
mMapView.zoomToBoundingBox(boundingBox);
You can calculate boundingBox by BoundingBox.fromGeoPoints(geoPoints)
fun zoomToBounds(points: List<LatLng>) {
val geoPoints = points.map { GeoPoint(it.latitude, it.longitude) }
val boundingBox = BoundingBox.fromGeoPoints(geoPoints)
mapView.zoomToBoundingBox(boundingBox, true)
}
It is also possible to have some paddings by using zoomtoBoundingBox overloaded method and setting the pBorderSizeInPixels parameter
public double zoomToBoundingBox(
final BoundingBox pBoundingBox,
final boolean pAnimated,
final int pBorderSizeInPixels,
final double pMaximumZoom,
final Long pAnimationSpeed
)

Inherited variables are not reading correctly when using bitwise comparisons

I have a few classes set up for a game, with XMapObject as the base, and XEntity, XEnviron, and XItem inheriting it.
MapObjects have a number of flags, one of them being MAPOBJECT_SOLID. My problem is that XEntity is the only class that correctly detects MAPOBJECT_SOLID. Both Items are Environs are always considered solid by the game, regardless of the flag's state. What is important is that Environs and Item should almost never be solid.
Each class has a very basic preliminary constructor, just initializing all varibles to zero or NULL. During the CreateX() phase, Objects are linked into the map, set into a linked linked list.
Both XItem and XEnviron are a tad sloppy. They are both new, and in the middle or my debugging attempts.
Here are the relevent code samples:
XMapObject:
#define MAPOBJECT_ACTIVE 1
#define MAPOBJECT_RENDER 2
#define MAPOBJECT_SOLID 4
class XMapObject : public XObject
{
public:
Uint8 MapObjectType,Location[2],MapObjectFlags;
XMapObject *NextMapObject,*PrevMapObject;
XMapObject();
void CreateMapObject(Uint8 MapObjectType);
void SpawnMapObject(Uint8 MapObjectLocation[2]);
void RemoveMapObject();
void DeleteMapObject();
void MapObjectSetLocation(Uint8 Y,Uint8 X);
void MapObjectMapLink();
void MapObjectMapUnlink();
};
XMapObject::XMapObject()
{
MapObjectType = 0;
Location[0] = 0;
Location[1] = 1;
NextMapObject = NULL;
PrevMapObject = NULL;
}
void XMapObject::CreateMapObject(Uint8 Type)
{
MapObjectType = Type;
}
void XMapObject::SpawnMapObject(Uint8 MapObjectLocation[2])
{
if(!(MapObjectFlags & MAPOBJECT_ACTIVE)) { MapObjectFlags += MAPOBJECT_ACTIVE; }
Location[0] = MapObjectLocation[0];
Location[1] = MapObjectLocation[1];
MapObjectMapLink();
}
XEntity:
XEntity *StartEntity = NULL,*EndEntity = NULL;
class XEntity : public XMapObject
{
public:
Uint8 Health,EntityFlags;
float Speed,Time;
XEntity *NextEntity,*PrevEntity;
XItem *IventoryList;
XEntity();
void CreateEntity(Uint8 EntityType,Uint8 EntityLocation[2]);
void DeleteEntity();
void EntityLink();
void EntityUnlink();
Uint8 MoveEntity(Uint8 YOffset,Uint8 XOffset);
};
XEntity::XEntity()
{
Health = 0;
Speed = 0;
Time = 1.0;
EntityFlags = 0;
NextEntity = NULL;
PrevEntity = NULL;
IventoryList = NULL;
}
void XEntity::CreateEntity(Uint8 EntityType,Uint8 EntityLocation[2])
{
CreateMapObject(EntityType);
SpawnMapObject(EntityLocation);
if(!(MapObjectFlags & MAPOBJECT_SOLID) { MapObjectFlags += MAPOBJECT_SOLID; }
EntityFlags = ENTITY_CLIPPING;
Time = 1.0;
Speed = 1.0;
EntityLink();
}
void XEntity::EntityLink()
{
if(StartEntity == NULL)
{
StartEntity = this;
PrevEntity = NULL;
NextEntity = NULL;
}
else
{
EndEntity->NextEntity = this;
}
EndEntity = this;
}
XEnviron:
class XEnviron : public XMapObject
{
public:
Uint8 Effect,TimeOut;
void CreateEnviron(Uint8 Type,Uint8 Y,Uint8 X,Uint8 TimeOut);
};
void XEnviron::CreateEnviron(Uint8 EnvironType,Uint8 Y,Uint8 X,Uint8 TimeOut)
{
CreateMapObject(EnvironType);
Location[0] = Y;
Location[1] = X;
SpawnMapObject(Location);
XTile *Tile = GetTile(Y,X);
Tile->Environ = this;
MapObjectFlags = MAPOBJECT_ACTIVE + MAPOBJECT_SOLID;
printf("%i\n",MapObjectFlags);
}
XItem:
class XItem : public XMapObject
{
public:
void CreateItem(Uint8 Type,Uint8 Y,Uint8 X);
};
void XItem::CreateItem(Uint8 Type,Uint8 Y,Uint8 X)
{
CreateMapObject(Type);
Location[0] = Y;
Location[1] = X;
SpawnMapObject(Location);
}
And lastly, the entity move code. Only entities are capable of moving themselves.
Uint8 XEntity::MoveEntity(Uint8 YOffset,Uint8 XOffset)
{
Uint8
NewY = Location[0] + YOffset,
NewX = Location[1] + XOffset;
if((NewY >= 0 && NewY < MAPY) && (NewX >= 0 && NewX < MAPX))
{
XTile *Tile = GetTile(NewY,NewX);
if(Tile->MapList != NULL)
{
XMapObject *MapObject = Tile->MapList;
while(MapObject != NULL)
{
if(MapObject->MapObjectFlags & MAPOBJECT_SOLID)
{
printf("solid\n");
return 0;
}
MapObject = MapObject->NextMapObject;
}
}
if(Tile->Flags & TILE_SOLID && EntityFlags & ENTITY_CLIPPING)
{
return 0;
}
this->MapObjectSetLocation(NewY,NewX);
return 1;
}
return 0;
}
What is wierd, is that the bitwise operator always returns true when the MapObject is an Environ or an Item, but it works correctly for Entities. For debug I am using the printf "Solid", and also a printf containing the value of the flag for both Environs and Items.
Any help is greatly appreciated, as this is a major bug for the small game I am working on. I am also very new at Object Oriented programming, anything tips, suggestions and/or criticism are also welcome.
Your problem appears to be that you never initialize MapObjectFlags in any classes other than XEnviron so, as a basic type, it will have an unspecified value in XItem, XEntity and other XMapObject derived objects. I suggest that, as a member of XMapObject you explicitly initialize it to a known value.
As a rule, it is generally a good idea to ensure that all members of basic type are explicitly initialized in the initializer list of every constructor that you define.
e.g.
XMapObject()
: MapObjectFlags(0)
, // ... other initializers
{
// Other initializations
}
You can't (legally) be calling XEntity::MoveEntity on a MapObject or Environ because they don't have such a method. If you're using static_cast to change your object pointer into an XEntity so you can call MoveEntity on it, then you really have no guarantees about how the bit operation will work. In some implementations, things may appear to work in MoveEntity, but what's actually happening is it's interpreting the other object's memory as an XEntity. When it tries to access the offset where it believes MapObjectFlags exists, it's not actually there and always has that bit set to 1.
I figured out the problem earlier today - It didn't have any relation to OO programming, inheritance, or bitwise; it was a simple scope error.
The problem was in the fact that during my quick test to get an Environ in game, I declared the new variable inside of the control switch sequence, so the next time any control was used, the Environ would act in unpredictable ways.
switch(Event.key.keysym.sym)
{
...
case SDLK_c: { XEnviron Environ; Environ.InitEnviron(...); }
...
}